nginx laravel5.6以下版本关于定时任务的部署(实现onOneServer)

场景

  • laravel5.6项目通过nginx负载均衡部署, 如果在每台real server上都部署crontab 则回导致定时任务被重复执行的问题, 但是如果放在一台机器上,则会导致所有的资源都是消耗在同一台机器, 没有充分利用资源
  • ps: 总结一下, 需求就是在不重复执行定时任务的请款下,充分的利用的real server

参考资料

+laravel5.6 scheduling#running-tasks-on-one-server

分析

laravel5.6 onOneServer()
laravel5.6 可以通过内置的onOneServer方法解决问题

To utilize this feature, your application must be using the memcached or redis cache driver as your application’s default cache driver. In addition, all servers must be communicating with the same central cache server

使用onOneServer的前提是应用使用memcached 或者redis作为默认的cache driver; 并且real server使用的是同一台机器上的cache server
If your application is running on multiple servers, you may limit a scheduled job to only execute on a single server. For instance, assume you have a scheduled task that generates a new report every Friday night. If the task scheduler is running on three worker servers, the scheduled task will run on all three servers and generate the report three times. Not good!

当代码部署在多台机器上的时候,可能会需要限制定时任务只在一台real server上运行; 例如 三台机器部署代码,设置周五晚上运行一个周五晚上生成报告的定时任务。如果三台server都有部署,则生成了三次报告

To indicate that the task should run on only one server, use the onOneServer method when defining the scheduled task. The first server to obtain the task will secure an atomic lock on the job to prevent other servers from running the same task at the same time:

当定义定时任务的时候,如果要指定定时任务只在一台机器上运行可以使用onOneServer方法; 第一个捕获这个任务的server会对这个task生成一个原子锁,这样可以阻止其他real server在同一时间运行这一台机器

$schedule->command(‘report:generate’)
->fridays()
->at(‘17:00’)
->onOneServer();

  • 那低于laravel5.6的版本应该怎么解决问题呢?

解决(laravel5.6以下版本的实现方法)

  • 换个思路
  • 在一台机器上运行定时任务
    • 这样确保定时任务不会重复执行
  • 充分利用real server
    • 定时任务,通过JOB的方式实现, 这样可以通过队列在运算分散到各个real server
    • laravel5.5 Scheduling Queued Jobsschedule 提供了一个快捷语法
      • $schedule->job(new Heartbeat)->everyFiveMinutes();

猜你喜欢

转载自blog.csdn.net/cominglately/article/details/86514653