CronJob
WaCron class is a powerful tool for scheduling
Using the WaCron
Class for Scheduling Tasks
The WaCron
class is a powerful tool for scheduling and managing tasks at specified intervals. Below are practical examples demonstrating how to use this class effectively in different scenarios.
Example 1: Basic Task Execution Every 5 Seconds
To execute a task every 5 seconds, use the following configuration:
Explanation:
- Schedule:
'*/5 * * * * *'
indicates the job should run every 5 seconds. - Callback Function: Prints the execution count each time the task runs.
Example 2: Delayed Start
If you want to start the task but delay the first execution, set delayFirstMoment
to true
:
Explanation:
delayFirstMoment: true
: The first execution will only occur after the first scheduled interval, i.e., 10 seconds after starting.
Example 3: Immediate Execution on Start
To execute the task immediately upon starting, set delayFirstMoment
to false
:
Explanation:
delayFirstMoment: false
: Executes the task immediately upon starting, then continues according to the cron schedule.
Example 4: Convert Duration to Cron Expression
If you prefer to use a duration instead of a cron string, convert a Duration
to a cron expression:
Explanation:
WaCron.durationToCron(Duration(seconds: 30))
: Converts the duration into a cron expression that runs every 30 seconds.
Example 5: Stopping a Cron Job
To stop a running cron job and release resources:
Explanation:
cronJob.close()
: Stops the cron job and releases resources. In this example, the cron job will be stopped after running for 5 minutes.
Summary
The WaCron
class allows you to:
- Schedule tasks to run at specified intervals using cron expressions.
- Delay the first execution or run immediately.
- Convert
Duration
to cron expressions. - Stop the cron job and clean up resources.
By configuring WaCron
with the appropriate schedule and options, you can handle various task scheduling needs in your application efficiently.