frcho / crontask
使用 Symfony 4、5 实现cron任务的简单方法
1.1.1
2020-12-07 15:43 UTC
Requires
- php: >=7.0
- doctrine/doctrine-bundle: ^2.0.8
- doctrine/orm: ^v2.5.14
- symfony/console: ^3.4|^4.0|^5.0
- symfony/form: ^3.4|^4.0|^5.0
- symfony/twig-bundle: ^3.4|^4.0|^5.0
README
为每个琐碎的任务创建新的cron作业是一项耗时的工作。而且,根据您的应用程序托管的环境,您可能并不总是能够随时添加cron作业到系统中。
安装
步骤 1:下载Bundle
打开命令行并执行以下命令以下载此Bundle的最新稳定版本
$ composer require frcho/crontask 1.1.0
此命令需要您全局安装了Composer,请参阅Composer文档中的安装章节。
使用Symfony命令和Doctrine实体实现基于间隔的cron任务
名为"CronTask"的Doctrine实体
如果我们快速回顾一下要求,我们会注意到我们希望我们的任务能够做到以下几点
在指定的时间间隔内运行执行某些操作
这听起来就像它所表现的那样简单。首先,我们将创建一个CronTask实体,我们可以将其持久化到我们的数据库中。这个实体应该包含一个可以执行的数组动作。我们将使用Symfony命令作为我们的操作。如果每个任务都有自己的标识符也将很有用。
创建您的命令
<?php namespace App\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class CronTasksDefaultCommand extends Command { protected function configure() { $this->setName('crontasks:default')->setDescription('Creates the commands by default in database.'); } protected function execute(InputInterface $input, OutputInterface $output): int { set_time_limit(0); ini_set('memory_limit', '-1'); $container = $this->getApplication()->getKernel()->getContainer(); $defaultCommands = array( array( "name" => "Example asset symlinking task", "interval" => 2, // Run once every 2 minutes, "range" => 'minutes', "commands" => 'assets:install --symlink web', "isHide" => false, /* "isHide == true, if you have enable view for this bundle, This command doesn't show in the view schedule task" */ "enabled" => true ), array( "name" => "Example asset task", "interval" => 1, // Run once every hour "range" => 'hours', "commands" => 'cache:clear', "enabled" => false ), ); $container->get('frcho.crontask_default')->setArrayCommands($defaultCommands); return 0; } }
##注意:范围支持
- 分钟
- 小时
- 天
用法
运行其他命令的命令
$ php bin/console crontasks:run
填充数据库的命令,包括由crontask:run运行的命令
$ php bin/console crontasks:default
执行crontasks:default后,您现在应该有一个CronTask在您的数据库中,准备好执行。
现在,您可以自己执行 php bin/console crontasks:run。或者将其添加为实际cron作业,每几分钟执行一次,如下所示
$ crontab -e Now add your cron job: # Run every five minutes */5 * * * * php path-your-project/bin/console crontasks:run And there you have it. One task to rule them all.
更新数据库模式
bin/console doctrine:schema:update --force
许可协议
此Bundle受MIT许可协议约束。