pub struct Scheduler<Tz: TimeZoneExt> { /* private fields */ }
Expand description
The interface for interacting with the scheduler.
When launching a scheduler, the scheduler and its service are created simultaneously with a channel connecting them. Job insert and remove messages are sent to the service for automatic management. When the scheduler is dropped, so too will the service its attached to exit.
use smol::Timer;
use chrono::offset::Local;
let (mut scheduler, service) = Scheduler::<Local>::launch(Timer::after);
// Creates a job which executes every 3 seconds.
let job = Job::cron("1/3 * * * * *").unwrap();
let fizz_id = scheduler.insert(job, |id| println!("Fizz")).await;
// Creates a job which executes every 5 seconds.
let job = Job::cron("1/5 * * * * *").unwrap();
let buzz_id = scheduler.insert(job, |id| println!("Buzz")).await;
service.await;
Implementations§
Source§impl<Tz: TimeZoneExt + 'static> Scheduler<Tz>
impl<Tz: TimeZoneExt + 'static> Scheduler<Tz>
Sourcepub async fn insert(
&mut self,
job: Job<Tz>,
command: impl Fn(JobId) + Send + Sync + 'static,
) -> JobId
pub async fn insert( &mut self, job: Job<Tz>, command: impl Fn(JobId) + Send + Sync + 'static, ) -> JobId
Insert a job into the scheduler with the command to call when scheduled.
// Creates a job which executes every 3 seconds.
let job = Job::cron("1/3 * * * * *").unwrap();
let fizz_id = scheduler.insert(job, |id| println!("Fizz")).await;
Sourcepub async fn remove(&mut self, job: JobId)
pub async fn remove(&mut self, job: JobId)
Remove a scheduled job from the scheduler.
scheduler.remove(fizz_id).await;
Sourcepub fn launch<F, T, X>(
timer: T,
) -> (Self, impl Future<Output = ()> + Send + Sync + 'static)
pub fn launch<F, T, X>( timer: T, ) -> (Self, impl Future<Output = ()> + Send + Sync + 'static)
Initializes the scheduler and its connected service.
The API is designed to not rely on any async runtimes. This is achieved by returning a future to allow the caller to decide how it should be executed, and taking a function for handling sleeps. You can choose to spawn the returned future, or avoid spawning altgether and await it directly from the same thread.
§Smol runtime
let (mut scheduler, sched_service) = Scheduler::<Local>::launch(smol::Timer::after);
smol::spawn(sched_service).detach();
§Tokio runtime
let (mut scheduler, sched_service) = Scheduler::<Local>::launch(tokio::time::sleep);
tokio::spawn(sched_service);