Yii2编程指南:运行Cron服务的方法

Yii2编程指南:运行Cron服务的方法

如果您问“Yii 是什么?”查看我之前的教程:Yii 框架简介,其中回顾了 Yii 的优点,并概述了 2014 年 10 月发布的 Yii 2.0 的新增功能。嗯>

在这个使用 Yii2 编程系列中,我将指导读者使用 Yii2 PHP 框架。在今天的教程中,我将与您分享如何利用 Yii 的控制台功能来运行 cron 作业。

过去,我在 cron 作业中使用了 wget — 可通过 Web 访问的 URL 来运行我的后台任务。这引发了安全问题并存在一些性能问题。虽然我在我们的启动系列安全性专题中讨论了一些减轻风险的方法,但我曾希望过渡到控制台驱动的命令。对于 Yii2 来说,这相当简单。

对于今天的示例,我将在我的 Twixxr 站点上演示基于控制台的 cron 命令,我在本 Twitter API 剧集中对此进行了描述。由于速率限制和性能管理问题,Twitter API 非常依赖高效、可靠的 cron 任务。所以这是一个很好的例子,可以与您分享。

在开始之前,我要重申:我始终感谢您的想法和反馈。如果您有问题或主题建议,请在下面的评论中发表您的想法。您也可以直接通过 Twitter @reifman 联系我。

什么是 Cron?

维基百科将 cron 描述为“类 Unix 计算机操作系统中基于时间的作业调度程序”。这是相当准确的。基本上,cron 运行我们运行 Web 服务所需的所有后台任务,从日志管理和备份到 API 请求再到数据库清理。

要查看服务器上现有的 cron 作业,您通常输入 sudo crontab -l 并看到如下内容:

# Edit this file to introduce tasks to be run by cron. 1. 1. Each task to run has to be defined through a single line 1. indicating with different fields when the task will be run 1. and what command to run for the task 1. 1. To define the time you can provide concrete values for 1. minute (m), hour (h), day of month (dom), month (mon), 1. and day of week (dow) or use '*' in these fields (for 'any').# 1. Notice that tasks will be started based on the cron's system 1. daemon's notion of time and timezones. 1. 1. Output of the crontab jobs (including errors) is sent through 1. email to the user the crontab file belongs to (unless redirected). 1. 1. For example, you can run a backup of all your user accounts 1. at 5 a.m every week with: 1. 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/ 1. 1. For more information see the manual pages of crontab(5) and cron(8) 1. 1. m h dom mon dow command */3 * * * * wget -O /dev/null https://meetingplanner.io/daemon/frequent */15 * * * * wget -O /dev/null http://meetingplanner.io/daemon/quarter 0 * * * * wget -O /dev/null http://meetingplanner.io/daemon/hourly 15 1 * * * wget -O /dev/null http://meetingplanner.io/daemon/overnight 40 2 * * * /usr/sbin/automysqlbackup 15 3 * * 5 wget -O /dev/null http://meetingplanner.io/daemon/weekly 30 2 * * 1 /opt/letsencrypt/letsencrypt-auto renew >> /var/log/le-renew.log 登录后复制