确保cron作业不会重复执行同一个作业两次

jei2mxaa  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(352)

我在mysql数据库中有一个类似任务的列表,还有一个php脚本,它一次执行一个任务。完成后,它会将标志从挂起更改为完成
我想通过添加更多在同一数据库上运行的脚本(最多20个)来提高性能。如何确保这些脚本不会执行同一任务两次,即处理表中的同一行
提前谢谢!

dxxyhpgq

dxxyhpgq1#

一种可能的方法是:
您可以更改的数据类型 flag 列到 ENUM 键入(如果尚未键入)。它将有三个可能的枚举值: pending , in_process , done .
当选择一个 pending 任务要做,做一个明确的 LOCK 在table上;以便其他会话无法更新它。
代码示例:

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;

相关问题