代码之家  ›  专栏  ›  技术社区  ›  Arbazz Hussain

有没有办法让@periodic\u task只在调用时运行,它会在项目启动时自动运行?

  •  1
  • Arbazz Hussain  · 技术社区  · 8 年前

    有没有什么办法 periodic_task 我明白了,只能随叫随到 Pingit() 只要我运行django应用程序 python manage.py runserver

    @periodic_task(run_every=crontab(minute="*/1"),options={"task_id":task_name})
        def Pingit():
            print('Every Minute Im Called')
    

    Pingit .

    1 回复  |  直到 8 年前
        1
  •  1
  •   Will Keeling    8 年前

    你最好使用 @task 为此,并让它在执行后重新排队,例如:

    @app.task
    def pingit(count=0):
        if count < 60 * 24 * 7:  # 7 days in minutes
            print('Every Minute Im Called')
    
            # Queue a new task to run in 1 minute
            pingit.apply_async(kwargs={'count': count + 1}, countdown=60)
    
    # Start the task manually
    pingit.apply_async()
    

    如果需要向函数添加位置参数,可以使用 args name

    @app.task
    def pingit(name, count=0):
        if count < 60 * 24 * 7:  # 7 days in minutes
            print('Every Minute Im Called')
    
            # Queue a new task to run in 1 minute
            pingit.apply_async(args=[name], kwargs={'count': count + 1}, countdown=60)
    
    # Start the task manually
    pingit.apply_async(args=['MyName'])