【问题标题】:Make sure the cron job won't do the same job twice确保 cron 作业不会两次执行相同的作业
【发布时间】:2018-10-27 06:21:18
【问题描述】:

我在 mysql 数据库中有一个类似任务的列表和一个 PHP 脚本,它一次取出 1 个任务并执行它。完成后,它会将标志从 pending 更改为 done

我想通过添加更多在同一数据库上运行的脚本(最多 20 个)来提高我的性能。我如何确保这些脚本不会两次执行相同的任务,即。处理表中的同一行

提前致谢!

【问题讨论】:

    标签: mysql cron execution overlapping


    【解决方案1】:

    一种可能的方法是:

    • 您可以将flag 列的数据类型更改为ENUM 类型(如果还没有的话)。它将具有三个可能的枚举值:pendingin_processdone
    • 在选择pending任务时,请在表格上进行显式@ 987654322;以便没有其他会话可以更新它。

    代码示例:

    LOCK TABLES tasks_table WRITE; -- locking the table for read/write
    
    -- Selecting a pending task to do
    SELECT * FROM tasks_table
    WHERE flag = 'pending' 
    LIMIT 1;
    
    -- In application code (PHP) - get the Primary key value of the selected task.
    
    -- Now update the flag to in_process for the selected task
    UPDATE tasks_table 
    SET flag = 'in_process' 
    WHERE primary_key_field = $selected_value;
    
    • 最后,不要忘记释放显式锁。

    代码:

    -- Release the explicit Lock
    UNLOCK TABLES;
    

    【讨论】:

      猜你喜欢
      • 2019-03-07
      • 2017-07-31
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多