【发布时间】:2022-05-06 17:07:36
【问题描述】:
这是我第一次尝试实现任务调度,我正在尝试在某个时间发送自动电子邮件:
在实现我的cron之前我先在一个普通的类中手动测试了我的邮件发送代码,看看有没有报错,没有报错,邮件发送成功了。
之后,我开始实现任务调度
Democron.php
protected $signature = 'demo:cron';
protected $description = 'Command description';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$tasks = Task::all();
$date = Carbon::now()->toDateTimeString();
foreach ($tasks as $task) {
if($task->completed_at != null){
$validad = $task->completed_at;
$receiver_id = User::findOrFail($task->user_id);
if($date > $validad){
$details = [
'task_id' =>$task->id,
'receiver_id' => $receiver_id
];
$subject = 'TeamWork - Você tem tarefas em atraso!';
$view = 'emails.project.delaydtask';
Mail::to($receiver_id->email)->send(new SendMail($details, $subject, $view));
Log::info('Email enviado com sucesso para '.$receiver_id->email);
}
}
}
}
内核.php
protected $commands = [
DemoCron::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('demo:cron')
->twiceDaily(12, 15)
->timezone('Africa/Maputo');
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
我在 CPANEL 上添加到 CRON JOBS 并将每天两次设置为 12 和 15
/usr/local/bin/php /.......myProjectPath/artisan schedule:run >> /dev/null 2>&1
我在我的 DemoCron.php 中打印了一个 LOG,看看它是否真的有效
结果 1: 当我每分钟选择一次计划时,它会根据 Democron.php 中的所有条件打印我的日志,但它没有t 发送电子邮件。
结果 2: 当我选择某个时间(每天两次或每天一次)时,我的 LOG 不打印任何内容,并且它不发送电子邮件。
我做错了什么?请帮帮我!
更新
我用来手动发送电子邮件的 SendMail 类可以完美运行,
但预定的电子邮件没有发送
class SendMail extends Mailable
{
use Queueable, SerializesModels;
public $details, $subject, $view;
public function __construct($details, $subject, $view)
{
$this->details = $details;
$this->subject = $subject;
$this->view = $view;
}
public function build()
{
return $this->subject($this->subject)
->view($this->view, ['details' => $this->details]);
}
}
【问题讨论】: