Ruby 定时任务之一(初步尝试)

     最近工作需要用到定时任务。原来写java的时候也用到过类似的Scheduler的功能。

     Ruby语言中也有同样功能的工具。rufus-scheduler。下面介绍一下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
 3 
 4 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 end
11 scheduler.join

输出结果:

1 2013-10-25 08:38:09 -0700
2 process begin----
3 2013-10-25 08:39:36 -0700
4 Time is up
5 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
 3 
 4 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 end
11 scheduler.join

输出结果:

1 2013-10-25 08:45:53 -0700
2 process begin----
3 2013-10-25 08:45:53 -0700
4 Time is up
5 order pizza

   2:在从此刻开始间隔多长时间执行

    

1 require 'rufus-scheduler'
2 scheduler = Rufus::Scheduler.new
3 
4 puts Time.new
5 scheduler.in '1s' do
6   puts Time.new
7   puts 'Hello...Word'
8 end
9 scheduler.join

输出结果:

1 2013-10-25 02:56:02 -0700
2 2013-10-25 02:56:03 -0700
3 Hello... Word

 3:在特定时间间隔内执行

     

1 require 'rufus-scheduler'
2 scheduler = Rufus::Scheduler.new
3 
4 puts Time.new
5 scheduler.every '1s' do
6   puts Time.new
7   puts 'Hello... Word'
8 end
9 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... Word
10 2013-10-25 03:05:44 -0700
11 Hello... Word

 4:在特定的cron时间执行

 1 require 'rufus-scheduler'
 2 scheduler = Rufus::Scheduler.new
 3 
 4 puts Time.new
 5 puts 'process begin----'
 6 scheduler.cron '/1 * * * *' do
 7   puts Time.new
 8   puts 'Hello word'
 9 end
10 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 -0700
10 Hello word
11 2013-10-25 09:02:00 -0700
12 Hello word
13 2013-10-25 09:03:00 -0700
14 Hello word

至于cron的使用方法,请参考cron相关文章。

此文只是Ruby定时任务的初步,在下一篇中和大家一起进入深一步的分析。

原文地址:https://www.cnblogs.com/fantiantian/p/3388367.html