【问题标题】:Auto-Update a MySQL row exactly after n seconds after the insert插入后 n 秒后自动更新 MySQL 行
【发布时间】:2020-12-11 12:27:44
【问题描述】:

我在 MySQL 中有这张表:

CREATE TABLE `comp` (
  `id_comp` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `id_exam` int(11) unsigned NOT NULL,
  `date_start` datetime NOT NULL,
  `date_stop` datetime DEFAULT NULL,
  `status` tinyint(1) DEFAULT '1' COMMENT '1=open, 0=closed, -1=forced',
  PRIMARY KEY (`id_comp`)
);

在另一个表(考试)中,我允许 max_execution_time,例如600 秒。 600 秒后,如果状态已打开 (1),我将更新行,将状态更改为 -1 并填充 data_stop 字段(使用 CURRENT_DATETIME)。

我已经通过外部脚本 (resque) 实现了这一点。 我应该使用数据库本身,也许使用存储过程吗? MySQL 可以吗?

我尝试使用存储过程和SLEEP(),但它阻止了执行(并且异步执行似乎不可行)。另一方面,EVENT 语法不能接受参数。

有什么想法吗?

谢谢

附言否则,我可以用 Postgresql 做吗?

【问题讨论】:

  • 插入您可能会执行此操作的行 create event procedure。或者,您可以创建每秒执行一次的永久过程,并在这些行存在时执行操作。
  • 从另一面看——这有意义吗?如果超过 10 分钟,您可以在检索期间检查并返回“强制”状态,并在任何更新期间检查并根据需要更改状态。

标签: mysql sql stored-procedures scheduled-tasks


【解决方案1】:

如果您只是想让数据“看起来”正确,那么您可以使用视图。视图可以即时计算状态:

create view v_comp as
    select c.id_comp, c.id_exam, c.date_start,
           (case when date_end is not null then date_end
                 when now() > c.date_start + interval e.max_execution_time second
                 then c.date_start + interval e.max_execution_time second
            end) as date_end,
           (case when date_end is not null then status
                 when now() > c.date_start + interval e.max_execution_time second
                 then -1
            end) as status
    from comp c join
         exams e
         on c.id_exam = e.id_exam;

这种方法的优点是数据总是是正确的。计算机上的延迟可以将事情延迟一两秒——或者更长的时间,这没有问题。

您实际上可以通过多种方式更新数据:

  • 批处理,例如每天一次或每小时一次用于需要更新的行。
  • 您可以使用排队系统,将update 插入到队列中。在 MySQL 中,这可能会使用事件调度程序。

【讨论】:

    猜你喜欢
    • 2018-10-10
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多