Scheduling Task with CRONOS

Web API

In the Program.cs class of the API, configure as shown below:

The next step is to create the extension class CronJobExtensions, responsible for controlling the next scheduling of each task using the CronExpression:

Next, it is necessary to create the extension class ScheduledServiceExtensions responsible for registering the schedules:

And finally, let's create the class for scheduling the actions, in this example, we will create a schedule to be triggered every second and another to be triggered every minute. These two schedules are registered in the Program.cs class

Testing

To test the schedules, run the API and analyze the logs generated by Serilog in the application console:

None

It's possible to see that the task scheduling that checks the database is triggered every second, while the scheduling that sends emails is triggered every minute.

Conclusion

Cronos is a library for parsing Cron expressions and calculating the next occurrences, with it, it is possible to schedule important background tasks, examples: Perform database maintenance every morning, capture data from a source from time to time, creation of alerts, etc.

Share this post