Cyclic jobs in Yii and MySQL
When we are talking about some cyclic tasks executed periodically in PHP, most of us automatically thinks about CRON. It is not surprising, since it is very popular, easy to manage (available often even on shared hostings) and easy to code (it simply fires given PHP script).
However, there are four other ways you can achieve exactly the same in Yii/PHP. And many Yii developers may not be aware about some of them.
Here are some details on this matter, however, expect, that this article is only a brief list to initiate your further research. You won’t find ready, out-of-the-box solutions here.
Total five methods for executing time-based job schedules, that I know, are:
- [hosting] CRON,
- [PHP] a link in your application’s control panel, clicked periodically by admins,
- [Yii] writing own console command, called via
yiic command, executed periodically, by admins,
- [Yii] an extra code in
onBeginRequestevent executed upon each request, if conditions are met,
- [MySQL] using events in MySQL (if you’re using phpMyAdmin, go to
Eventstab after selecting a database).
If speaking about security, using console command seems to be most secure, as it assumes, that only user with access to console can fire particular command.
Disadvantage of this solution (as good as second one), is that it isn’t actually a periodic scheduler. Someone has to remember to execute that command (click that link) periodically. So, it isn’t the best solution for time-critical situations (for example: closing shop promotion at precisely marked time).
onBeginRequest event is my second choose, but you must carefully and perfectly write checking code, because this piece will be fired upon each request. Any mistake here will significantly reduce your overall application performance.
This solution is used for example in WordPress (the idea, of course, as WordPress is not written in Yii). Things like scheduled posts publications are triggered by first request to WordPress executed in given date or time.
MySQL events are also good choose, if only you can use this RDBMS and if only your admin (i.e. on shared host) didn’t block you from using events in MySQL.