【问题标题】:Select all rows with a date of right now [closed]选择日期为现在的所有行[关闭]
【发布时间】:2013-10-10 19:00:27
【问题描述】:

我需要创建一个每分钟运行一次的 cron 作业,并在 mysql 数据库中搜索日期字段等于当前日期和四舍五入到分钟的所有行。

我的问题是什么是正确的查询,也许是存储事件日期的最佳方式。

这里的基本用例是我已经安排了活动,我需要在安排这些活动的确切时间发送通知。这似乎是一件很常见的事情,但我无法确定这是否是最好的方法。

提前致谢。

【问题讨论】:

  • 您是否尝试过使用常规日期时间字段的 NOW() (dev.mysql.com/doc/refman/5.1/en/…) 并将两者都格式化为 YYYY-MM-DD HH:MM ?
  • 为什么不直接在任何软件进行调度时发送通知?或者也许使用在插入时触发的数据库触发器?

标签: php mysql laravel laravel-4


【解决方案1】:

为您的调度程序创建一个工匠命令:

文件: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');

创建一个调度器类:

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

【讨论】:

    【解决方案2】:

    也许你需要稍微改变一下逻辑。

    你可以让它变得更容易,只需实现这个查询块:

    ... WHERE date_field <= CURRENT_TIMESTAMP() AND processed = 0;
    

    请注意,我使用了 CURRENT_TIMESTAMP() 函数,这是因为查询速度,如果您将日期作为 unix 时间戳存储在 INTEGER 类型字段中,它将非常快

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 2018-07-05
      • 2018-07-27
      相关资源
      最近更新 更多