Three methods for executing periodic tasks (scheduled tasks) IN ruby: ruby periodic

Source: Internet
Author: User
Tags cron script

Three methods for executing periodic tasks (scheduled tasks) IN ruby: ruby periodic

1. Preface

Whether using ruby for system management or using rails for web development, periodic tasks may occur. They are scheduled to take a certain period of time (1 hour, 2 days ......) continuously triggered. In ruby, I think it is very convenient to use sidekiq for a one-time task, while for a periodic task, we need to use gems such as whenever, sidetiq, and clockwork.

2. whenever

First, whenever is based on the linux cron service. Therefore, there is no direct way to use the gem on the windows platform. Whenever should be regarded as a cron translator, which translates ruby code into a cron script, so that periodic tasks can be handed over to cron for actual completion. It may not be worth mentioning for shell programmers who are proficient in cron, but it is not for rubyist. First, we can use the ruby language to write the task code and control the code at the ruby level to avoid switching from some shell scripts. In addition, the cron command is very powerful, but I can't remember its command parameters. To avoid having to go to man's manual over and over again, the ruby syntax is quite friendly.

First, install whenever:

The Code is as follows:
$ Gem install whenever

Switch to the project folder where the task is written to ensure that there is a config folder under the folder. If you create a whenever task in the rails project, the config folder already exists.

The Code is as follows:
$ Cd/project
$ Wheneverize.

The whenverize command will create the schedule. rb file in the config folder. Our task code needs to be defined in this file. The following is an example of the schedule. rb file:

The Code is as follows:
Every 30. minutes do
Runner "Blog. parseAll"
Every 30. minutes,: at => 17 do
Runner "PostWeibo. post"
Every 15. minutes do
Runner "WeiBo. update"
Every 30. minutes,: at => 20 do
Runner "RSSGenerator. generate"
Every,: at => '2: 00 am' do
Command "cd/var/www/mzread/current/public & gunzip-c sitemap1.xml.gz> sitemap1.xml & touch sitemap1.xml"

For example, in the sample code, whenever defines three types of tasks by default: runner, rake, and command. We can also define our own tasks. For example, the following code defines the separation from the rails environment, types of ruby code executed independently:

The Code is as follows:
Job_type: ruby, "cd: path &/usr/bin/ruby ': task'. rb"

Every: hour do
Ruby 'have _ a_rest'

This example describes how to run the have_a_rest.rb script in the current folder every hour.

The following describes how to write a task to the cron service.

The Code is as follows:
$ Whenever # The whenever without parameters will display the code of the conversion cron task and will not be written to the cron task table.
$ Whenever-w # Write to cron task table and start execution
$ Whenever-c # cancel a task

To view the cron task table, run the linux Command to list all cron tasks:
The Code is as follows:
$ Crontab-l

3. sidetiq

Sidetiq is a brother of sidekiq. If sidekiq is used in the rails project to process Background tasks, it is natural to use sidetiq to deliver periodic tasks.

Install sidetiq:
The Code is as follows:
$ [Sudo] gem install sidetiq

Define periodic tasks:
The Code is as follows:
Class MyWorker
Include Sidekiq: Worker
Include Sidetiq: Schedulable

Recurrence {daily}

Def perform
# Do stuff...

Like sidetiq, sidekiq relies on redis messages to process messages. When the rails project is started, these periodic tasks are automatically loaded and executed.

4. clockwork

Clockwork is the same as sidetiq and does not depend on cron. It can adapt to the "cross-platform" requirement. The following is a sample code (clock. rb ):

The Code is as follows:
Require 'clockwork'
Include Clockwork

Handler do | job |
Puts "Running # {job }"

Every (10. seconds, 'frequent. job ')
Every (3. minutes, 'less. frequent. job ')
Every (1. hour, 'hourly. job ')

Every (, 'midnight. job',: at => '00: 00 ')

Start the task:
The Code is as follows:
$ Clockwork clock. rb
Starting clock for 4 events: [frequent. job less. frequent. job hourly. job midnight. job]
Triggering frequent. job

If you want to bring the rails environment, add the following to the task file:
The Code is as follows:
Require './config/boot'
Require './config/environment'

How can php be regularly executed on a daily basis?

Php cannot be executed on a regular basis every day. Only java or c can be used. Because php does not access the page, it won't make code, but there is a way to save the country.
You can write a page that is scheduled to be executed on a daily basis. Then, depending on your operating system, you can perform scheduled tasks to access this page regularly.
Use the task scheduler function for windows
For linux, use the scheduled task Cron and use curl to access your page at the scheduled time. Below I will only post the linux solution, because the general servers are linux, windows will

====================================== Linux cron entry ==================== ======================

Cron is a scheduled execution tool in Linux. It can run jobs without manual intervention. Since Cron is a built-in service in Linux, but it does not automatically get up, you can use the following methods to start and close this service: /sbin/service crond start // start the service/sbin/service crond stop // close the service/sbin/service crond restart // restart the service/sbin/service crond reload // reload you can also configure to automatically start the service when the system starts: in/etc/rc. d/rc. add/sbin/service crond start at the end of the local script. Now the Cron service is already in the process, and we can use this service, the Cron Service provides the following APIs: 1. directly use the crontab command to edit the cron service and provide the crontab command to set the cron service. The following are some parameters and instructions for this command: crontab-u // set the cron service of a user., Generally, when executing this command, the root user needs this parameter crontab-l // to list the details of a user's cron service. crontab-r // Delete the cron service crontab-e of no user. // edit the cron service of a user, for example, view the cron settings of the root user: crontab-u root-l again, for example, root wants to delete the cron setting of fred: crontab-u fred-r when editing the cron service, the edited content has some formats and conventions. input: crontab-u root-e enters the vi editing mode. The edited content must conform to the following format: */1 ***** ls>. After the operating system is installed, the task scheduling command is started by default. The crond command periodically checks whether there is any job to be executed every minute. If there is any job to be executed, the job is automatically executed. 1. linux task scheduling is divided into the following two types: * system execution: The work to be executed by the system periodically, such as backing up system data and clearing cache * personal execution: the work that a user does on a regular basis, such as checking whether there are new emails on the email server every 10 minutes, can be set by each user. 2. crontab command option:-u specifies a user,-l lists the task plans of a user,-r deletes the task of a user, and-e edits the task of a user ...... remaining full text>

In linux, how does one regularly execute a command?

Linux has a system-level scheduled task service named cron. The command in the terminal is crontab.
Crontab-u root-l: view all scheduled tasks of the root user.
Crontab-u root-e is the scheduled task for editing the root user. entering this parameter enters the vi editing mode.
The editing format is fixed. You can search for the cron command usage.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.