在Python Flask中,如何每60秒执行一些操作,然后更新所有用户页面?

huangapple go评论68阅读模式
英文:

How can I perform some stuff every 60 seconds in Python Flask, and then update all user pages?

问题

我目前正在开发一个回合制在线网页游戏。我希望每位玩家能够选择一个动作,并且每60秒,所有玩家选择的动作应该同时执行(如果没有选择动作,则执行默认动作)。我计划将选择的动作保存在SQL数据库中。唯一的问题是,我不知道如何每60秒执行一次操作。

我尝试过使用asyncio,并阅读过Celery可能会帮助我,但我并不真正理解如何实现我需要的精确结果。据我理解,指南只帮助在Flask应用程序内使用这些内容,但不是与Flask应用程序同时。

英文:

I am currently working on an turn-based online webgame. I want every player to be able to choose a move, and every 60 seconds the chosen moves of all players should get performed simultaneously (if no move is chosen, a default move gets performed). I am planning to save the chosen move in a SQL database. The only problem is, I have no idea, how to perform something each 60 seconds.

I have tried to use asyncio and have read that Celery could help me, but I didn't really understood how to achieve exactly the result I need. As I understood, the guides were helping only to use the stuff inside the flask app, but not simultaneously with the flask app

答案1

得分: 1

你可以使用线程:

import threading
import time

def perform_task():
    print("执行任务")

def schedule_task():
    while True:
        perform_task()
        time.sleep(60)

thread = threading.Thread(target=schedule_task)
thread.start()
英文:

You can use threading:

import threading
import time

def perform_task():
    print("Performing task")

def schedule_task():
    while True:
        perform_task()
        time.sleep(60)

thread = threading.Thread(target=schedule_task)
thread.start()

huangapple
  • 本文由 发表于 2023年2月27日 04:48:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574922.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定