Laravel基于cron的定时执行任务

一个每天自动通过接口传输给客户服务器客户数据的案例,记录下

Posted by 昆山吴彦祖 on 2019.12.05

整个过程分了2部分,

1 、通过laravel和cron创建定时(每天临晨)执行任务

2、创建队列任务进行接口数据传输并记录传输结果(其实这一步理论上可以省略,但是为了防止传输过程中网络异常,用队列可以进行多次失败尝试)


参考: 文档  其他

创建定时任务

1、添加Cron到服务器

crontab -e 
//进入编辑模式 添加下面的内容:

* * * * * php /网站服务器路径/artisan schedule:run >> /dev/null 2>&1

2、定义调度

laravel可以通过  App\Console\Kernel 类的 schedule 方法中定义所有调度任务(任务可以是简单的php指令,也可以是队列任务、自定义Artisan指令来完成负责的逻辑)

php namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Jobs\SendCustomer;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
		// 定义一个定时调度任务,每天凌晨0点传输数据到OSD
		$schedule->job(new SendCustomer)->daily();

    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}



创建自动推送信息队列任务

队列的使用参考

php namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class SendCustomer implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
	public $tries = 2;//最大尝试次数
	public $timeout = 100;//最大尝试时间
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
      
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
      
      	Log::channel('single')->info('开始传输!');
		try{
			//获取客户数据
			//传输数据
			$response = json_decode(CURL($url, json_encode($params), $ispost, $https));
          
			if($response->code==0 ){
				Log::channel('single')->info('传输用户数据到OSD接口成功!');
			}else{
				throw new \Exception($response->getMessage());
			}
		}catch(\Exception $e){
			Log::channel('single')->info('传输用户数据到OSD接口失败:');          
          	Log::channel('single')->info($e->getMessage());
		}
    }
}


ps (测试阶段)

手动启动定时任务指令:php artisan schedule:run

如果是队列任务,重启任务之前一定要执行 php artisan queue:restart   (血淋淋的教训,队列任务有缓存机制,不重启会一直执行之前的队列任务,即使修改队列php文件也没用)



cron