如何从控制器执行 shell 命令

How to execute shell command from controller

我正在从事 CakePHP 项目。

我有一些任务要在后台执行,这可能需要很长时间才能完成。因此我使用了 cakephp-queue 插件(感谢 dev)。

现在我已将所有任务移动到 shell 中,每次用户单击按钮时,都会使用此功能从控制器创建一个新作业

$job = $this->QueuedJobs->createJob('Scan', [
   'server_id' => $id,
   'user' => $this->Auth->user('id'),
]);

这工作正常。但是为了执行任务,我需要从终端 运行 命令

bin/cake queue runworker

项目上线和部署时不可能。那么,如何在创建作业后立即从控制器中执行此命令?

您还没有理解任务的工作原理。重点是 不要 让控制器等待某事,也不要 运行 来自网络上下文的 shell。

再次阅读文档:https://github.com/dereuromark/cakephp-queue/tree/master/docs#setting-up-the-trigger-cronjob 你应该创建一个 cron 作业。

*/10 * * * * cd /full/path/to/app && bin/cake queue runworker -q

Make sure you use crontab -e -u www-data to set it up as www-data user, and not as root etc.

This would start a new worker every 10 minutes. If you configure your max life time of a worker to 15 minutes, you got a small overlap where two workers would run simultaneously. If you lower the 10 minutes and raise the lifetime, you get quite a few overlapping workers and thus more "parallel" processing power. Play around with it, but just don't shoot over the top.

它将拾取任务并更新任务状态。