【问题标题】:PHP Laravel Task Scheduling Best PracticePHP Laravel 任务调度最佳实践
【发布时间】:2017-05-08 09:25:28
【问题描述】:

我正在构建一个简单的应用程序,它将根据用户输入的时间安排启用/禁用广告集。

例如,用户可能希望他们的广告在上午 6 点至上午 9 点、下午 5 点至晚上 10 点以及其他所有时间都关闭。

安排这个的最佳方式是什么?我会将所有数据存储在 MYSQL 中,我是否应该有一个 cron/task 每分钟检查表中与时间匹配的行,然后启用/禁用函数?

继续该示例,该表可能包含列、时间、函数。

早上 6 点,启用 上午 9 点,停用 下午 5 点,启用 晚上 10 点,停用

我的问题是,如果我有 10,000 个左右的用户,这对于网络服务器来说是否太多了,或者有没有更有效的方法来做到这一点?

【问题讨论】:

  • 我不确定您是否需要计划任务,但也许我遗漏了一些东西。您不能只检查一个表格,看看当前时间是否在他们安排广告展示的时间?

标签: php mysql laravel cron task


【解决方案1】:

在下面的方法中,我们正在做的是......

  1. 有 2 个表格 - adsad_timings 为每个广告保存不同的 start_timeend_time...
  2. start_time(如 0600)和 end_time(如 0900)在哪里保存。所以,现在您只需检查当前时间(例如,它的2016-23-12 06:50:11)...您将其转换为0650
  3. 现在您找出所有 start_time 小于 650end_time 大于此的广告,以找出有效广告并执行反之则广告停止。
  4. 每 10 分钟运行一次...为每个用户提供 10 分钟的最小输入时间间隔...这样您每 10 分钟运行一次 cron 并在后台节省内存...。

你的桌子

ad
id | name | current_status | ....
 1 |  ... |      0         | .....

ad_timings
id | ad_id | start_time | end_time
1  |   1   |   600      |  900
1  |   1   |   1700     |  2200

你的模型

class Ad extends Model
{
  public function timings()
  {
    return $this->hasMany('App\Models\AdTimings');
  }
}

class AdTimings extends Model
{
  protected $table = 'ad_timings';

  public function ad()
  {
    return $this->belongsTo('App\Models\Ad')
  }
}

在你的调度器中

use Carbon\Carbon;
use App\Models\Ad;

class AdScheduler
{
  public function handle()
  {
    $now = Carbon::now();

    // This will convert current timestamp to something like
    // Timestamp: 2016-12-23 23:36:11
    // to
    // Now: 2336
    // Basically you are calculating time on the basis of hundreds..
    // Like people say... 1300 hours... get me?
    $now = $now->hour . $now->minute;

    // These are the ads to run
    // You can change their current_status field to 1 with update
    $adsToRun = Ad::whereHas('timings', function($query) use ($now) {
                  return $query->where('start_time', '<=', $now)
                               ->where('end_time', '>=', $now)
                })->get();

    // Ads to Stop
    // You can change their current_status field to 0 with update
    $adsToStop = Ad::whereHas('timings', function($query) use ($now) {
                  return $query->where('start_time', '>=', $now)
                               ->where('end_time', '<=', $now)
                })->get();
  }
}

【讨论】:

    猜你喜欢
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    相关资源
    最近更新 更多