我需要创建一个cron作业,它将每分钟运行一次,并在mysql数据库中搜索所有有一个日期字段等于当前日期和时间四舍五入到分钟的行。
我的问题是什么是正确的查询,也许是存储事件日期的最佳方式。
这里的基本用例是,我有预定的事件,我需要在计划这些事件的确切时间发送通知。这似乎是一件很普通的事情,但我很难弄清楚这是否是最好的方法。
提前谢谢。
发布于 2013-10-10 20:21:02
为调度程序创建一个手工命令:
文件: app/commands/CheckSchedule.php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class CheckScheduleCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'check:schedule';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Process scheduled messages.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(Scheduler $scheduler)
{
parent::__construct();
$this->scheduler = $scheduler;
}
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
$this->scheduler->check();
}
}告诉Artisan加载命令编辑文件app\start\artisan.php并添加:
Artisan::resolve('CheckScheduleCommand');创建Scheduler类:
class Scheduler {
public function check()
{
$date = \Carbon\Carbon::now();
// set the seconds to 59 to get the 'whole' minute in the
$date->second = 59;
/// this filter will get every notification not sent from now to the past
/// If your server got slow or something like that people will still be notified
$notifications = Schedule::where('notify_at','<=',$date)->where('notified',false)->get();
foreach($notifications as $notification)
{
$this->notify($notification);
}
}
public function notify($notification)
{
/// do whatever you need here to notify your user;
$notification->notified = true;
$notification->save();
}
}然后通过运行
php artisan check:schedule你可以用cron每分钟做一次
* * * * * /path/to/php /var/www/project/artisan check:schedule关于您的日期字段,您最好使用时间戳,更容易过滤,您可以使用验证者和变异器使用户使用它时友好,并且仍然将其存储为时间戳:http://laravel.com/docs/eloquent#accessors-and-mutators。
https://stackoverflow.com/questions/19304071
复制相似问题