Many Ruby developers use the awesome whenever gem for scheduling tasks in their projects, so do we and with ‘whenever’  scheduling tasks become so effortless that we absolutely loved it. Recently we have been deploying Crytal apps to production and Kemal is our framework of choice. During the process, we felt the urge to have something similar to whenever in Crystal for cron jobs and that’s when we discovered Schedule – a Crystal shard that provides a clear DSL to write periodic or scheduled tasks and there was no turning back.

Getting started

Add Schedule to your shard.yml file

you are all set to schedule your tasks, all you gotta do is require the schedule module as require "schedule"

Examples

Schedul’s API defines 2 important methods, .every and .after for periodic and scheduled execution of tasks respectively.

Periodic execution

For running a task periodically we have to pass in a valid interval as well as a block to the .every method. For example,

will print the message on every 3 seconds.

Similarly

will call the class method hourly_job every 1 hour

Scheduled execution

For scheduling tasks to run sometime in the future we can make use of the after method.

Stop and Retry jobs

Call Schedule.retry to retry a task and Schedule.stop to stop the executing a task

 Exception handlers

We can use Schedule.exception_handler to set an exception handler in our tasks

it is also possible to pass a proc to Schedule.exception_handler directly to set the exception handler

schedule.cr is still in the early stages of development and many options that we are familiar with using whenever – like running tasks on a specific day of the week are not available yet but are coming soon.

 Happy Hacking <3