Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Ruby 定时任务之一(初步尝试)

最近工作需要用到定时任务。原来写java的时候也用到过类似的Scheduler的功能。Ruby语言中也有同样功能的工具。rufus-scheduler。《Ruby for Rails中文版》.((美)David Black ).[PDF] http://www.linuxidc.com/Linux/2014-03/97569.htm重要文章阅读:Ruby入门--Linux/Windows下的安装、代码开发及Rails实战 http://www.linuxidc.com/Linux/2014-04/100242.htm下面介绍一下rufus-scheduler。 定义: a Ruby gem for scheduling pieces of code (jobs). It understands running a job AT a certain time, IN a certain time, EVERY x time or simply via a CRON statement.安装:gem install rufus-scheduler(gem安装是前提,再次不多言) 使用:rufus-scheduler可以指定在特定时间时执行,在从此刻开始间隔多长时间执行,在特定时间间隔内循执行,在特定的cron时间执行。例子如下:1:指定特定时间(或者超过指定时间)执行   1 require "rufus-scheduler" 2 scheduler = Rufus::Scheduler.new 34 puts Time.new 5 puts "process begin----" 6 scheduler.at "2013-10-25 08:39:36 -0700" do 7 puts Time.new 8 puts "Time is up" 9 puts "order pizza"10 end11 scheduler.join 输出结果:1 2013-10-25 08:38:09 -07002 process begin----3 2013-10-25 08:39:36 -07004 Time is up5 order pizza如果设置的at时间在程序运行之前,比如设置的at时间为:2013-10-25 08:39:36。程序运行时的时间为2013-10-25 08:34:36。那么程序运行时候就执行设置的事件举个例子:   1 require "rufus-scheduler" 2 scheduler = Rufus::Scheduler.new 34 puts Time.new 5 puts "process begin----" 6 scheduler.at "2013-10-25 08:39:36 -0700" do 7 puts Time.new 8 puts "Time is up" 9 puts "order pizza"10 end11 scheduler.join 输出结果:1 2013-10-25 08:45:53 -07002 process begin----3 2013-10-25 08:45:53 -07004 Time is up5 order pizza 2:在从此刻开始间隔多长时间执行  1 require "rufus-scheduler"2 scheduler = Rufus::Scheduler.new3 4 puts Time.new5 scheduler.in "1s" do6 puts Time.new7 puts "Hello...Word"8 end9 scheduler.join 输出结果: 1 2013-10-25 02:56:02 -07002 2013-10-25 02:56:03 -07003 Hello... Word3:在特定时间间隔内执行  1 require "rufus-scheduler"2 scheduler = Rufus::Scheduler.new3 4 puts Time.new5 scheduler.every "1s" do6 puts Time.new7 puts "Hello... Word"8 end9 scheduler.join 输出结果:  1 2013-10-25 03:05:38 -0700 2 2013-10-25 03:05:39 -0700 3 Hello... Word 4 2013-10-25 03:05:41 -0700 5 Hello... Word 6 2013-10-25 03:05:42 -0700 7 Hello... Word 8 2013-10-25 03:05:43 -0700 9 Hello... Word10 2013-10-25 03:05:44 -070011 Hello... Word 4:在特定的cron时间执行  1 require "rufus-scheduler" 2 scheduler = Rufus::Scheduler.new 34 puts Time.new 5 puts "process begin----" 6 scheduler.cron "/1 * * * *" do 7 puts Time.new 8 puts "Hello word" 9 end10 scheduler.join 输出结果:  1 2013-10-25 08:57:46 -0700 2 process begin---- 3 2013-10-25 08:58:00 -0700 4 Hello word 5 2013-10-25 08:59:00 -0700 6 Hello word 7 2013-10-25 09:00:00 -0700 8 Hello word 9 2013-10-25 09:01:00 -070010 Hello word11 2013-10-25 09:02:00 -070012 Hello word13 2013-10-25 09:03:00 -070014 Hello word 至于cron的使用方法,请参考cron相关文章。 此文只是Ruby定时任务的初步,在下一篇中和大家一起进入深一步的分析。