Unicron provides a simple mechanism for scheduling one-off and repeating tasks to execute at specific times in the background of a long-running Ruby process. The easiest way to set up a Unicron job is to call Unicron::schedule.
The delay parameter schedules a job to run a certain number of seconds in the future:
Unicron.schedule delay: 180 do |job| puts "Ramen's done." end
The at parameter schedules a job to run at a certain time. If the time has passed, the job runs immediately:
Unicron.schedule at: Time.parse('23:00') do |job| puts 'Go to bed!' end
The delay parameter can be combined with repeat to schedule a repeating job:
Unicron.schedule delay: 1, repeat: true do |job| puts Time.now.sec.odd? ? 'tick' : 'tock' end
If both at and delay are used with repeat, the job will first run at the time specified by at and then repeat every repeat seconds afterwards. If repeat is Numeric, it specifies the number of times to repeat the Job.
Unicron.schedule at: Time.parse('7:00'), delay: 600, repeat: 3 do |job| puts 'WAKE UP!' end
When both at and delay are specified, and at is in the past, Unicron will run the job at the first future even multiple of delay seconds after at. Although this sounds complicated, it's an easy way to make sure a job runs at the same time every day, or only at the top of the hour.
Unicron.schedule at: Time.parse('12:00'), delay: 86400 do |job| puts 'Time for lunch!' end
Unicron is not cron
Although Unicron serves many of the same purposes as cron, there are important distinctions between the two. Unicron runs in a background thread of a (presumably) long-running Ruby process like your web application. This makes it ideal for tasks that are lightweight, dependent on the main process, or which do not need to run unless the main process is also running. Unicron also requires no system administration, making it an attractive choice if you're authoring a turnkey gem that needs to run periodic tasks in the background.
On the other hand, cron is independent of any other processes and is always running in the background. This makes cron better suited for spawning heavyweight tasks which have limited interaction with the main process.