Yii scheduled tasks

Source: Internet
Author: User
Yii scheduler jobs

Original English/Scheduling Jobs With Yii

Sometimes there will be a long running or a lot of computing work in your application. we should not let users wait for the server to process them, but let them process them in the background. you may need to perform some operations very late, such as sending a user report at the end of a day. the solution to the preceding scenario is to create a queue and process it on a non-web client.

Heroku scheduler

Heroku provides an additional component called "Heroku scheduler", which can be executed every 10 minutes, every hour, or every day. we will use this scheduler to access our Yii Console Command (Yii Console Command ).

Queue

I will use a MySQL table as a queue, although some people think this is a bad design mode. the reason for doing so is that I will not encounter any problems mentioned in the article. you can also use any of the * MQ additional components you like.

Team List Migration (Migration)

The migration of the team list is very simple. it contains the execution timestamp (executed after this time), the actual execution time, whether the execution is successful, the operation to be executed, parameters, and optional execution results. we will discuss how to use these fields in console commands. (You can find these source code in https://github.com/aarondfrancis/yii-CronCommand)

$this->createTable('tbl_cron_jobs', array( 'id' => 'pk', 'execute_after' => 'timestamp', 'executed_at' => 'timestamp NULL', 'succeeded' => 'boolean', 'action' => 'string NOT NULL', 'parameters' => 'text', 'execution_result' => 'text' ));
CronJob model

The CronJob model is a standard model generated using Gii, except for the following two methods:

public function beforeValidate(){ if(gettype($this->parameters) !== "string"){ $this->parameters = serialize($this->parameters); } return parent::beforeValidate(); } public function afterFind(){ $this->parameters = unserialize($this->parameters); return parent::afterFind(); }

The beforeValidate method serializes any parameters. the afterFind method then deserializes them. for example, if we want to send a welcome email to a user two hours after registration, we should create a new CronJob and pass an array containing the user ID. the model will serialize this array and save it to the database. when we get it, the model will deserialize it.

Yii console commands

Now we have a model for work, Next let's take a look at the CronCommand we will run. (you can also get the source code in the https://github.com/aarondfrancis/yii-CronCommand). here I'll just talk about the key part.

In this example, the script entry point is the Index action. this is what we will call in the Heroku Scheduler. we will let the index action decide what will be processed. (This is only one of the processing methods. I like this because I only need to process logic in one place. if I add a new command to be processed, all I need to do is add it to CronCommand and it will process the new command the next time Heroku calls my index action. other optional methods may be to add the action {New} method for each New action, and add a New scheduled task to Heroku to call the New action. I prefer an entry: actionIndex .)

The first thing to do is to obtain the list of tasks to be processed. select a task whose current time is later than the execute_after time (meaning it should be executed) and which is not executed. sort by ID in ascending order, so that the first added task can be executed first. (If we have an execution queue, we may not see the earliest tasks unless we select them first)

$jobs = CronJob::model()->findAll('execute_after <:now AND executed_at IS NULL ORDER BY id ASC', array(':now'=>$now));

Next we will traverse all the tasks and process them. but we must first ensure that there are methods to process them. if so, call this method.

if(method_exists($this, $job->action)){ $result = $this->{$job->action}($job->parameters);

If you add a CronJob model whose action is "testJob", CronCommand calls the $ this-> testJob ($ job-> parameters) method when processing this task. if the result is FALSE, we will skip it and wait for the next processing. otherwise, an array with succeeded of the boolean type will be returned. execution_result any result you like.

Make it run

Now we have set the Cron command. you can run it in the protected folder through the terminal. /yiic to test. you can see the option "cron ". now you can try to run. /yiic cron. if a task exists in your table, you can see that it is being executed.

The rest is that we need to write a bash script running on Heroku. it is super simple and only needs two lines, as shown below:

export LD_LIBRARY_PATH=/app/php/ext bin/php www/protected/yiic.php cron

The first line sets the path required to run the PHP command line (thanks to Norbert? The second line calls our yiic. php cron command. save them as "heroku. sh "or other names, add it to your Heroku scheduler by entering the following command:

www/protected/heroku.sh

Now your actionIndex will run every 10 minutes, capture queue items (tasks), process them, and save the returned results.

Is there a problem?

If you have any questions, please let me know and I will do my best to help you.

Additional reading

If you want to read

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: info-contact@alibabacloud.com 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.