编辑:在 postgres 中每秒自动更新时间戳

问题描述

我在 postgres 数据库中有一个 local_date_time 列(没有时区的时间戳),并且需要根据速度每秒自动更新一次,例如 1x、2x(实时每 1 秒增加 2 秒)等等。 建议在 pgadmin 中或使用 python 脚本执行此操作的方法代码应该在服务器机器上持续运行。 我已经安排了这样的跑步,

            def autoupdate_userclock(userid,speed):
                """Auto update clock time based on speed."""
                try:
                    connection = psycopg2.connect(
                  # DB connection parameters )
        # Speed check - Increment based on speed
                    if speed == "1x":
                        x = timedelta(seconds=1)
                    elif speed == "2x":
                        x = timedelta(seconds=2)
                    elif speed == "3x":
                        x = timedelta(seconds=3) and so on
          
            # DB query to update timestamp based on speed
                    update_query = """ UPDATE users
                    set local_date_time = (local_date_time + %s)::timestamp where (local_date_time+%s)::timestamp<=Now()::timestamp 
    and userid =%s"""
            
          with connection.cursor() as cursor:
             cursor.execute(update_query,(x,x,userid))
          connection.commit()
                except Exception as e:
                    print(e)
            
            # Task scheduling
            connection = psycopg2.connect(#DB connection string) 
with connection.cursor() as cursor:
                cursor.execute("select userid,speed from users")
                t = cursor.fetchall()
            connection.close()
            for row in t:schedule.every(1).seconds.do(
autoupdate_userclock,row[0].strip(),row[1].strip())
# Keep running the pending tasks      
while True:
  schedule.run_pending()

任何有效的解决方案?

解决方法

你不能那样做,而且没有任何意义。

相反,像这样定义表:

CREATE TABLE sample (
   id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,...,base_timestamp timestamp with time zone NOT NULL,speed double precision NOT NULL
);

然后像查询一样

SELECT id,base_timestamp + (current_timestamp - base_timestamp) * speed
FROM sample;

然后在需要时在查询中计算时间戳。