Giter Site home page Giter Site logo

binchengzhao / delay-timer Goto Github PK

View Code? Open in Web Editor NEW
285.0 5.0 23.0 607 KB

Time-manager of delayed tasks. Like crontab, but synchronous asynchronous tasks are possible scheduling, and dynamic add/cancel/remove is supported.

License: Apache License 2.0

Rust 100.00%
delayed-tasks cron crontab schedule delay-timer smol tokio scheduling scheduling-engines

delay-timer's Introduction

delay-timer's People

Contributors

binchengzhao avatar chaaz avatar eliasyaoyc avatar pymongo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

delay-timer's Issues

task parameter error

Describe the bug
add parameters to task function will get error of lifetime.

run example s demo.r,

error[E0621]: explicit lifetime required in the type of `url`
  --> examples/demo.rs:81:10
   |
81 |         .spawn(body)
   |          ^^^^^ lifetime `'static` required

error[E0621]: explicit lifetime required in the type of `url`
  --> examples/demo.rs:68:16
   |
68 |       let body = create_async_fn_body!({
   |  ________________^
69 | |         if let Ok(mut res) = surf::get(url).await {
70 | |             dbg!(res.body_string().await.unwrap_or_default());
71 | |
...  |
74 | |         }
75 | |     });
   | |______^ lifetime `'static` required
   |
   = note: this error originates in the macro `create_async_fn_body` (in Nightly builds, run with -Z macro-backtrace for more info)

cargo +nightly build error as unsatisfied trait bounds

Describe the bug
i can not run cargo +nightly build as unsatisfied trait bounds.

To Reproduce
Steps to reproduce the behavior:

rustc version: rustc 1.76.0-nightly (a1a37735c 2023-11-23)
delay_timer commit 69a3867

  1. cd delay_timer
  2. cargo +nightly build

then error will show like:

error[E0277]: the trait bound `StrSearcher<'_, '_>: DoubleEndedSearcher<'_>` is not satisfied                                                                     [0/583]
    --> src/utils/parse.rs:371:83
     |
371  |         let mut sub_command_inner = command.trim().split_inclusive(angle_bracket).rev();
     |                                                                                   ^^^ the trait `DoubleEndedSearcher<'_>` is not implemented for `StrSearcher<'_, '_>`
     |
     = help: the following other types implement trait `DoubleEndedSearcher<'a>`:
               CharSearcher<'a>
               CharArraySearcher<'a, N>
               CharArrayRefSearcher<'a, 'b, N>
               CharSliceSearcher<'a, 'b>
               CharPredicateSearcher<'a, F>
     = note: required for `std::str::SplitInclusive<'_, &str>` to implement `DoubleEndedIterator`
note: required by a bound in `rev`
    --> /home/chenmc/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:3399:23
     |
3397 |     fn rev(self) -> Rev<Self>
     |        --- required by a bound in this associated function
3398 |     where
3399 |         Self: Sized + DoubleEndedIterator,
     |                       ^^^^^^^^^^^^^^^^^^^ required by this bound in `Iterator::rev`

error[E0599]: the method `next` exists for struct `Rev<SplitInclusive<'_, &str>>`, but its trait bounds were not satisfied
    --> src/utils/parse.rs:374:14
     |
373  | /         sub_command_inner
374  | |             .next()
     | |             -^^^^ method cannot be called on `Rev<SplitInclusive<'_, &str>>` due to unsatisfied trait bounds
     | |_____________|
     |
     |
    ::: /home/chenmc/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/str/iter.rs:1216:1
     |
1216 |   pub struct SplitInclusive<'a, P: Pattern<'a>>(pub(super) SplitInternal<'a, P>);
     |   --------------------------------------------- doesn't satisfy `_: DoubleEndedIterator`
     |
    ::: /home/chenmc/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/rev.rs:15:1
     |
15   |   pub struct Rev<T> {
     |   ----------------- doesn't satisfy `Rev<std::str::SplitInclusive<'_, &str>>: Iterator`
     |
     = note: the following trait bounds were not satisfied:
             `std::str::SplitInclusive<'_, &str>: DoubleEndedIterator`
             which is required by `Rev<std::str::SplitInclusive<'_, &str>>: Iterator`

Some errors have detailed explanations: E0277, E0599.
For more information about an error, try `rustc --explain E0277`.
error: could not compile `delay_timer` (lib) due to 2 previous errors

Expected behavior
compile ok

Screenshots

Desktop (please complete the following information):

  • OS: archlinux

Feature request: `DelayTimer` check if ID is in use

Is your feature request related to a problem? Please describe.
I'd like to be able to check if a task with a specific ID is already being handled by DelayTimer, so I can avoid overwriting accidentally by inserting a new task with the same ID

Describe the solution you'd like

impl DelayTimer {
    pub fn has_task(&self, id: u64) -> bool {
        todo!()
    }
}

Describe alternatives you've considered
A workaround I considered was trying to remove a task then re-adding it if it existed, however DelayTimer::remove_task doesn't return the task being removed

Additional context
For use in my upcoming project

rust 1.75版本与delay-timer 0.11.4版本不兼容,1.74.1没有问题

error[E0277]: the trait bound StrSearcher<'_, '_>: DoubleEndedSearcher<'_> is not satisfied
--> /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/delay_timer-0.11.4/src/utils/parse.rs:371:83
|
371 | let mut sub_command_inner = command.trim().split_inclusive(angle_bracket).rev();
| ^^^ the trait DoubleEndedSearcher<'_> is not implemented for StrSearcher<'_, '_>
|
= help: the following other types implement trait DoubleEndedSearcher<'a>:
CharSearcher<'a>
CharArraySearcher<'a, N>
CharArrayRefSearcher<'a, 'b, N>
CharSliceSearcher<'a, 'b>
CharPredicateSearcher<'a, F>
= note: required for std::str::SplitInclusive<'_, &str> to implement DoubleEndedIterator
note: required by a bound in rev
--> /rustc/82e1608dfa6e0b5569232559e3d385fea5a93112/library/core/src/iter/traits/iterator.rs:3397:5

error[E0599]: the method next exists for struct Rev<SplitInclusive<'_, &str>>, but its trait bounds were not satisfied
--> /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/delay_timer-0.11.4/src/utils/parse.rs:374:14
|
373 | / sub_command_inner
374 | | .next()
| | -^^^^ method cannot be called on Rev<SplitInclusive<'_, &str>> due to unsatisfied trait bounds
| |_____________|
|
--> /rustc/82e1608dfa6e0b5569232559e3d385fea5a93112/library/core/src/str/iter.rs:1216:1
|
= note: doesn't satisfy _: DoubleEndedIterator
--> /rustc/82e1608dfa6e0b5569232559e3d385fea5a93112/library/core/src/iter/adapters/rev.rs:15:1
|
= note: doesn't satisfy Rev<std::str::SplitInclusive<'_, &str>>: Iterator
|
= note: the following trait bounds were not satisfied:
std::str::SplitInclusive<'_, &str>: DoubleEndedIterator
which is required by Rev<std::str::SplitInclusive<'_, &str>>: Iterator

Some errors have detailed explanations: E0277, E0599.
For more information about an error, try rustc --explain E0277.
error: could not compile delay_timer (lib) due to 2 previous errors

an error occurls when use delay-timer 0.10.0

report an error when use delay-timer 0.10.0
I try run 1000 jobs in my program,ceveral minitue later,when process running, some error appeard

2021-11-22T08:56:18.222587252+08:00 - INFO - src/main.rs -line=>29 - dt_test - ==== All job is be init! ====
2021-11-22T08:56:30.354993232+08:00 - ERROR - /home/test/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/delay_timer-0.10.0/src/timer/event_handle.rs -line=>199 - delay_timer::timer::event_handle - Fn : `quit_one_task_handler`, No task-handle-index found (task-id: 453 , record-id: 6868351392860475493)
2021-11-22T08:56:30.375546872+08:00 - ERROR - /home/test/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/delay_timer-0.10.0/src/timer/event_handle.rs -line=>199 - delay_timer::timer::event_handle - Fn : `quit_one_task_handler`, No task-handle-index found (task-id: 78 , record-id: 6868351392860475444)
2021-11-22T08:56:30.380463067+08:00 - ERROR - /home/test/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/delay_timer-0.10.0/src/timer/event_handle.rs -line=>199 - delay_timer::timer::event_handle - Fn : `quit_one_task_handler`, No task-handle-index found (task-id: 561 , record-id: 6868351392860475452)
2021-11-22T08:56:30.386620506+08:00 - ERROR - /home/test/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/delay_timer-0.10.0/src/timer/event_handle.rs -line=>199 - delay_timer::timer::event_handle - Fn : `quit_one_task_handler`, No task-handle-index found (task-id: 502 , record-id: 6868351392860475446)
2021-11-22T08:56:30.394059243+08:00 - ERROR - /home/test/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/delay_timer-0.10.0/src/timer/event_handle.rs -line=>199 - delay_timer::timer::event_handle - Fn : `quit_one_task_handler`, No task-handle-index found (task-id: 37 , record-id: 6868351392860475469)
2021-11-22T08:56:30.417319172+08:00 - ERROR - /home/test/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/delay_timer-0.10.0/src/timer/event_handle.rs -line=>199 - delay_timer::timer::event_handle - Fn : `quit_one_task_handler`, No task-handle-index found (task-id: 164 , record-id: 6868351392860475457)

After this error,the program is still running,I can not know if there is some effection.
my program

#[async_std::main]
async fn main() -> Result<()>{
    log4rs::init_file("conf/log4rs.yaml", Default::default()).unwrap();
    info!("begin");
    let delay_timer = DelayTimerBuilder::default().build();
    for i in 0..1000{
        let r = build_task_async_execute_process(i);
        match r {
            Ok(task) => {
                let r = delay_timer.add_task(task);
                match r {
                    Ok(_) => info!("init task id = [{}]", i),
                    Err(e) => info!("{}", e)
                } 
            },
            Err(e)=> info!("{}", e)
        }
    }
    info!("==== All job is be init! ====");
    thread::sleep(Duration::from_secs(3600*6));
    Ok(delay_timer.stop_delay_timer()?)
}

fn build_task_async_execute_process(task_id:u64) -> Result<Task, TaskError> {
    let mut task_builder = TaskBuilder::default();
    let cmd_string = String::from("sh tester/test_script.sh");
    info!("cmd_string = [{}]", &cmd_string);
    let body = dt_functions::unblock_process_task_fn(cmd_string);
    task_builder
        .set_frequency_repeated_by_cron_str("* * * * * *".into())
        .set_task_id(task_id)
        .set_maximum_running_time(10)
        .set_maximum_parallel_runnable_num(1)
        .spawn(body)
}

also can see at my test project
https://github.com/elderbig/delay_timer-test

relevant issue #28

Can not transmit args to shell

Can not transmit args to shell
I run a shell script for test,follow samples,like this:

let body = unblock_process_task_fn("sh test_vars.sh>>try_spawn.txt".into());

it can run well.

I want put some arg into shell, then I rewrite like bellow:

let body = unblock_process_task_fn("sh test_vars.sh>>try_spawn.txt  xxx".into());

this is test_vars.sh

t=`date`
echo $t -- "I run [ $1 ]"

The shell can run correct manualy,but nothing appeared,no message write into try_spawn.txt.
I try another way use environment variable,like:

let body = unblock_process_task_fn("TASK_ID=1 sh test_vars.sh>>try_spawn.txt".into());

and script modify like this:

t=`date`
echo $t -- "I run [ $TASK_ID ]"

How to complete this demo with delay-timer?

Code is as follow, questions are in the code.

Cargo.toml

[dependencies]
delay_timer = "0.10.1"

main.rs


use delay_timer::prelude::*;
use anyhow::Result;
use smol::Timer;
use std::time::Duration;



fn main() {
     //1、a timer start from 1 to 50000 millisecond.
            //let mut current_time= 1;

     //2、if the current_time equals some numbers, do somethings.
            if current_time =2000 {
                //do something 1
            } 
            if current_time =39999 {
                //do something 2
            } 
            //...
   
}

cyclic package dependency once this package is enabled

Once add this package to cargo.toml, I will get following error, anyway to get around this please?

error: cyclic package dependency: package `ahash v0.7.4` depends on itself. Cycle:
package `ahash v0.7.4`
    ... which is depended on by `hashbrown v0.11.2`
    ... which is depended on by `indexmap v1.7.0`
    ... which is depended on by `serde_json v1.0.64`
    ... which is depended on by `wasm-bindgen v0.2.74`
    ... which is depended on by `js-sys v0.3.51`
    ... which is depended on by `getrandom v0.2.3`
    ... which is depended on by `ahash v0.7.4`
    ... which is depended on by `actix-http v3.0.0-beta.8`
    ... which is depended on by `actix-web v4.0.0-beta.8`
    ... which is depended on by `actix-cors v0.6.0-beta.2`

build error

error when build version 0.10.0

cargo clean
cargo update
cargo build

error message

error[E0308]: mismatched types
   --> src/utils/parse.rs:308:9
    |
308 |         Ok(process_linked_list)
    |         ^^^^^^^^^^^^^^^^^^^^^^^ expected enum `error::CommandChildError`, found struct `anyhow::Error`
    |
    = note: expected enum `std::result::Result<_, error::CommandChildError>`
               found enum `std::result::Result<_, anyhow::Error>`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `delay_timer` due to previous error

set_frequency_repeated_by_cron_str cannot work

set_frequency_repeated_by_cron_str cannot work, v0.11.3

task_builder
    .set_task_id(1)
    .set_frequency_repeated_by_cron_str("@secondly")
    .set_maximum_parallel_runnable_num(1)
    .spawn_async_routine(body)

only execute once, but set_frequency_repeated_by_seconds(1) works correctly

Many jobs sometimes

Describe the bug

#[async_std::main]
async fn main() -> Result<()> {
    let conf = reader::read_config::read("conf/config.toml");
    log4rs::init_file("conf/log4rs.yaml", Default::default()).unwrap();
    let delay_timer = DelayTimerBuilder::default().build();
    let mut i:u64 = 0;
    for s in conf.service.unwrap() {
        i = i + 1;
        //If a task_id is used,new task will be ignore by insert_task fn.
        let begin_time = Local::now().naive_local();
        let shell_task_instance_chain = delay_timer.
            insert_task(build_task_async_execute_process(i,&s)?)?;
        let _ = shell_task_instance_chain
            .next_with_async_wait()
            .await?
            .cancel_with_async_wait()
            .await?;
        let end_time = Local::now().naive_local();
        info!("use [{0}] by task [{1}] init", (end_time - begin_time).num_seconds(), i);
    }

    info!("All job inited");
    for _ in 0..180 {
        thread::sleep(Duration::from_secs(60));
    }
    // No new tasks are accepted; running tasks are not affected.
    Ok(delay_timer.stop_delay_timer()?)
}

I config 100 jobs in a configuration file conf/config.toml,and init them in a loop,sometimes,it is remaining some jobs can not be init.output like:

2021-11-17T19:06:56.221273177+08:00 - INFO - src/main.rs -line=>39 - testcron - use [1] by task [1] init
2021-11-17T19:06:58.221268818+08:00 - INFO - src/main.rs -line=>39 - testcron - use [1] by task [2] init
2021-11-17T19:06:56.221273177+08:00 - INFO - src/main.rs -line=>39 - testcron - use [1] by task [3] init
2021-11-17T19:06:58.221268818+08:00 - INFO - src/main.rs -line=>39 - testcron - use [1] by task [4] init
....
....
2021-11-17T19:07:00.221238386+08:00 - INFO - src/main.rs -line=>39 - testcron - use [1] by task [59] init
2021-11-17T19:07:02.221417702+08:00 - INFO - src/main.rs -line=>39 - testcron - use [2] by task [60] init
2021-11-17T19:07:04.221640690+08:00 - INFO - src/main.rs -line=>39 - testcron - use [2] by task [61] init
2021-11-17T19:07:06.221278580+08:00 - INFO - src/main.rs -line=>39 - testcron - use [1] by task [62] init
2021-11-17T19:07:08.221419039+08:00 - INFO - src/main.rs -line=>39 - testcron - use [2] by task [63] init
2021-11-17T19:07:10.221318266+08:00 - INFO - src/main.rs -line=>39 - testcron - use [1] by task [64] init

then,it do nothing for a long time,some remainding jobs not appeared any more.I try tokio, there is the same problem.

Scheduler running is not correct run in UTC/Local mode

Hi @BinChengZhao
There are some errors in UTC mode, would you like to have a look at this, thank you.

Describe the bug
Scheduler running is not correct in UTC mode

To Reproduce
define a task scheduler like this, run in UTC mode:

        let task_builder = TaskBuilder::default()
            .set_frequency_repeated_by_cron_str(&dotenv::var("0 15 06 * * * *“)
            .set_schedule_iterator_time_zone(ScheduleIteratorTimeZone::Utc)
            .set_task_id(1)
            .spawn(body)?;

The task will be run one hour in advance(UTC: 05:15), also run in Local mode.

Environment:
Ubuntu Linux 20,
delay_timer: main branch and feature/for_le_rust_156 branch.

无法编译通过

error[E0554]: #![feature] may not be used on the stable release channel
--> /Users/lr/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/delay_timer-0.2.1/src/lib.rs:205:1
|
205 | #![feature(linked_list_cursors)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error[E0554]: #![feature] may not be used on the stable release channel
--> /Users/lr/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/delay_timer-0.2.1/src/lib.rs:206:1
|
206 | #![feature(doc_cfg)]
| ^^^^^^^^^^^^^^^^^^^^

error[E0658]: use of unstable library feature 'split_inclusive'
--> /Users/lr/.cargo/registry/src/mirrors.ustc.edu.cn-61ef6e0cd06fb9b8/delay_timer-0.2.1/src/utils/parse.rs:149:52
|
149 | let mut sub_command_inner = command.trim().split_inclusive(angle_bracket).rev();
| ^^^^^^^^^^^^^^^
|
= note: see issue #72360 rust-lang/rust#72360 for more information

error: aborting due to 3 previous errors

Some errors have detailed explanations: E0554, E0658.
For more information about an error, try rustc --explain E0554.
error: could not compile delay_timer.

Add more details when error

No more detail informations when error
LIke issue #25 I ment, I can not recive more information for debug.
Trace information should be print when error appeared

feature requests: update deps

such as:
event-listener which has ^4 released
lru which has ^0.12.0 released - introduced BC, and need manually fix.
dashmap which has ^5 released

How to set a microsecond interval for task

Hi delay-timer guys, how to set a microsecond intervals for a task.
From source-code, I can only find seconds-related function, and I can't use a cron string to generate a microsecond task, right?

The TimerEvent::AppendTaskHandle event should always be sent before The TimerEvent::FinishTask event.

Describe the bug
When the task instance is running too fast, The TimerEvent::FinishTask event will be sent before The TimerEvent::AppendTaskHandle event. Subsequent task instances will not run again.

To Reproduce
Steps to reproduce the behavior:

  1. add tokio::time::sleep(std::time::Duration::from_secs(2)).await before
    self.send_timer_event(task_id, tmp_task_handler_box).await;
  2. run a repeat task with maxinum_parallel_runnable_num = 1;
  3. If the task instance ends in less then 2 second, it will get parallel_runnable_num>=maxinum_parallel_runnable_num doesn't run it.

Expected behavior
Subsequent task instances can run again.

Set a daily 00:00:00 trigger task, from April 2 every day trigger time into 01::00:00

Describe the bug
设置了一个每天00:00:00触发的任务,从4月2号开始每天触发时间变成01::00:00了,不知道是否和时令有关.

To Reproduce
程序从3月份开始运行,4月2号前都是正常触发的.
计时器设置:
let task = TaskBuilder::default()
.set_frequency_repeated_by_cron_str("0 0 0 * * * *")
.set_task_id(1)
.spawn_async_routine(body)
.unwrap();

Desktop (please complete the following information):

  • OS: Ubuntu 18.04 LTS
  • delay-timer :0.11.1
  • timezone: Asia/Shanghai
  • rustflags: ["--cfg", "unsound_local_offset"]

examples/demo_async_std.rs run error when duration 30s

examples/demo_async_std.rs run error

To Reproduce
add a time to continue,like bellow

    thread::sleep(Duration::from_secs(20));
    Ok(delay_timer.stop_delay_timer()?)

edit function build_task_async_execute_process() ,when shedule like "*/1 * * * * * *",it is run well.

fn build_task_async_execute_process() -> Result<Task, TaskError> {
    let mut task_builder = TaskBuilder::default();

    let body = unblock_process_task_fn("ls -l >> ./try_spawn.txt".into());
    task_builder
        .set_task_id(3)
        .set_frequency_repeated_by_cron_str("*/1 * * * * * *")
        .set_maximum_running_time(10)
        .set_maximum_parallel_runnable_num(1)
        .spawn(body)

when use schedule like "*/3 * * * * * *",that run task every 3 second, I got a error

fn build_task_async_execute_process() -> Result<Task, TaskError> {
    let mut task_builder = TaskBuilder::default();

    let body = unblock_process_task_fn("ls -l >> ./try_spawn.txt".into());
    task_builder
        .set_task_id(3)
        .set_frequency_repeated_by_cron_str("*/3 * * * * * *")
        .set_maximum_running_time(10)
        .set_maximum_parallel_runnable_num(1)
        .spawn(body)

error like this:

create_async_fn_body!
Error: TaskInstance event get failed.

Caused by:
    receiving from an empty channel

Desktop (please complete the following information):

  • OS: linux

other
Can you help me get more ditails for error?

delay_timer rebuilds every time.

Describe the bug
When cargo build is run on a project that depends on delay-timer, it will always rebuild, even if no changes have been made.

To Reproduce
Steps to reproduce the behavior:

  1. Create a new project with cargo new --bin test_proj
  2. Add delay_timer = "0.9.0" to the dependencies section of Cargo.toml
  3. Run cargo build multiple times in succession

Every time cargo build is run, both delay_timer and the test_proj itself are recompiled.

Expected behavior
cargo build should not recompile anything if there have been no changes since the last compile.

Screenshots
N/A

Desktop (please complete the following information):

  • OS: ubuntu 20
  • delay_timer version: 0.9.0

"set_frequency_once" always execute immediately.

Describe the bug
set_frequency_once_by_seconds(5)
The function is executed immediately instead of being delayed for some time

To Reproduce

use std::time::Duration;

use delay_timer::prelude::{DelayTimerBuilder, ScheduleIteratorTimeZone, TaskBuilder};

#[tokio::main]
async fn main() {
    let body = || async {
        println!("running: {}", chrono::Local::now());
    };

    println!("start: {}", chrono::Local::now());
    let new_task = TaskBuilder::default()
        .set_task_id(1)
        .set_schedule_iterator_time_zone(ScheduleIteratorTimeZone::Local)
        .set_frequency_once_by_seconds(5)
        .set_maximum_parallel_runnable_num(1)
        .spawn_async_routine(body)
        .unwrap();

    let delay_timer = DelayTimerBuilder::default().build();
    delay_timer.add_task(new_task).unwrap();

    tokio::time::sleep(Duration::from_secs(15)).await;
    println!("end: {}", chrono::Local::now());
}
delay_timer = { version = "0.11.0", features = ["status-report"] }
chrono = "0.4.19"
tokio = { version = "1", features = ["full"] }

Result

start: 2022-04-22 10:56:01.732017356 +08:00
running: 2022-04-22 10:56:02.793417770 +08:00
end: 2022-04-22 10:56:16.796830865 +08:00

Expected behavior
Expect a five-second delay.

Desktop (please complete the following information):

  • OS: Linux version 3.10.0-957.el7.x86_64 (gcc version 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) )
  • Rust: rustc 1.59.0 (9d1b2106e 2022-02-23)

Run task delay for an hour in UTC mode

Describe the bug
Run task delay for an hour in UTC mode

To Reproduce
There are three task in a DelayTimerBuilder, two tasks run in time, but the first one task run delay for an hour.

code:

        //delay_timer
        let delay_timer = DelayTimerBuilder::default()
            .tokio_runtime_by_default()
            .build();

        //Task1: renew symbols
        let body_renew_sym = create_async_fn_tokio_body!({
            if let Err(err) = base::init_symbol_list().await {
                error!("Initial symbols list error: {}", err);
            }
        });
        let task_builder_renew_sym = TaskBuilder::default()
            .set_frequency_repeated_by_cron_str(&dotenv::var("50 00 22 * * * *").unwrap())
            .set_schedule_iterator_time_zone(ScheduleIteratorTimeZone::Utc)
            .set_task_id(1)
            //.set_maximum_running_time(600)
            .spawn(body_renew_sym)?;
        delay_timer.add_task(task_builder_renew_sym)?;

        //Task2: calculate D1 data and save to D1.csv file
        let body_d1 = create_async_fn_tokio_body!({
            csv::calculate_all_d1_ohlc();
        });
        let task_builder_d1 = TaskBuilder::default()
            .set_frequency_repeated_by_cron_str(&dotenv::var("0 10 22 * * Monday,Tuesday,Wednesday,Thursday,Friday *").unwrap())
            .set_schedule_iterator_time_zone(ScheduleIteratorTimeZone::Utc)
            .set_task_id(2)
            .spawn(body_d1)?;
        delay_timer.add_task(task_builder_d1)?;

        //Task4: calculate historical ohlc
        let body_ohlc = create_async_fn_tokio_body!((db_pool){
            if let Err(err) = csv::cron_sync_ohlc_to_db(&db_pool_ref).await {
                error!("Cron sync ohlc to database error: {}", err);
            }
        });
        let task_builder_ohlc = TaskBuilder::default()
            .set_frequency_repeated_by_cron_str(&dotenv::var("0 20 22 * * Monday,Tuesday,Wednesday,Thursday,Friday *").unwrap())
            .set_schedule_iterator_time_zone(ScheduleIteratorTimeZone::Utc)
            .set_task_id(4)
            .spawn(body_ohlc)?;
        delay_timer.add_task(task_builder_ohlc)?;

Info logs:

2022-02-08T01:00:51.690533645+02:00 INFO sync::base::base - Get active symbol from http api, len= 870

2022-02-08T00:20:00.484920457+02:00 INFO sync::csv::csv_file - Begin to sync cron calculate ohlc data and send to database...

2022-02-08T00:10:00.484385080+02:00 INFO sync::csv::csv_file - Calculate D1 file from tick data file

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.