Running Periodic Tasks Without cron or at


You want to write a self-contained Ruby program that performs a task in the background at a certain time, or runs repeatedly at a certain interval.


Fork off a new process that sleeps until its time to run the Ruby code.

Heres a program that waits in the background until a certain time, then prints a message:

	# lunchtime.rb

	def background_run_at(time)
	 fork do
	 sleep(1) until >= time

	today =
	noon = Time.local(today.year, today.month,, 12, 0, 0)
	raise Exception, "Its already past lunchtime!" if noon <

	background_run_at(noon) { puts "Lunchtime!" }

The fork command only works on Unix systems. The win32-process third-party add on gives Windows a fork implementation, but its more idiomatic to run this code as a Windows service with win32-service.


With this technique, you can write self-contained Ruby programs that act as though they were spawned by the at command. If you want to run a backgrounded code block at a certain interval, the way a cronjob would, then combine fork with the technique described in Recipe 3.12.

	# reminder.rb
	def background_every_n_seconds(n)
	 fork do
	 loop do
	 before =
	 interval = n-(
	 sleep(interval) if interval > 0

	background_every_n_seconds(15*60) { puts Get back to work! }

Forking is the best technique if you want to run a background process and a foreground process. If you want a script that immediately returns you to the command prompt when it runs, you might want to use the Daemonize module instead; see Recipe 20.1.

See Also

  • Both the win32-process and the win32-service libraries are available at
  • Recipe 3.12, "Running a Code Block Periodically"
  • Recipe 20.1, "Running a Daemon Process on Unix"



Date and Time



Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming


Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration

Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399 © 2008-2020.
If you may any questions please contact us: