每30秒运行一次Laravel方法 [英] Running a Laravel method every 30 seconds

查看:418
本文介绍了每30秒运行一次Laravel方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在应用程序上调用特定的URL时,我有一个方法可以运行.它处理数据库队列中的行.该间隔设置为Cron可能的最小间隔,即. 1分钟.这需要下降到30秒,所以我想知道如何最好地实现这一目标.

I have a method that runs when I call a specific URL on my application. It processes rows in a database queue. The interval is set as lowest interval possible with Cron, ie. 1 minute. This needs dropping to 30 seconds, so I'm wondering how best to achieve this.

我当时想我可以在我的脚本中建立一个循环,以使该代码运行两次,并在这段时间之间睡眠30秒,但是我想知道是否有比这更干净的方法.

I was thinking I could build a loop into my script that runs the code twice, with a sleep of say 30 seconds in between, but I'm wondering if there's a cleaner way than this.

还有,是否可以从命令行运行此方法,而无需调用实际的URL?

Also, is there a way of running this method from the command line, without the need to call an actual URL?

推荐答案

此答案受到这一个的强烈启发

您可以按原样保留您的代码.要每分钟两次调用它,您可以添加第二个cronjob,并让一个cronjob在执行任务之前30秒钟进入睡眠状态.

You can leave your code as it is. To call it twice a minute you can add a second cronjob and let one cronjob sleep 30 seconds before executing the task.

* * * * * /path/to/executable param1 param2
* * * * * ( sleep 30 ; /path/to/executable param1 param2 )

这有两个优点

  1. 您的代码无需担心执行时间和执行次数(例如,如果您手动调用它,则无需运行两次!)

  1. Your code doesn't need to worry about when and how many times it is executed (e.g. if you call it manually it doesn't need to run twice!)

如果代码需要10秒才能执行所有操作,则在函数内部使用sleep时将出现延迟.这样您就不会了.

If your code takes 10 seconds to execute everything you would have a delay when using sleep inside of your function. This way you don't.

这篇关于每30秒运行一次Laravel方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆