我在 mysql 数据库中有一个类似任务的列表,还有一个 PHP 脚本,它一次取出 1 个任务并执行它。完成后,会将标志从pending更改为done
我想通过添加在同一数据库上运行的更多脚本(最多 20 个)来提高性能。我如何确保这些脚本不会执行相同的任务两次,即。处理表中的同一行
提前致谢!
最佳答案
一种可能的方法是:
- 您可以将
flag
列的数据类型更改为ENUM
类型(如果还没有)。它将具有三个可能的枚举值:pending
、in_process
、done
。 - 选择要执行的
待处理
任务时,请执行明确的LOCK
在 table 上;这样其他 session 就无法更新它。
代码示例:
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;
关于mysql - 确保 cron 作业不会重复执行相同的作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53019288/