Search code examples
djangodatabasedjango-modelsweb-frameworks

Django: reset a specific field of a model every hour


I have a field in one of my models in django which I want to be reset every hour. (i.e. at each o'clock its value becomes zero)

How can I do this task? Can I schedule a function in django?

As you know we can define EVENTs and TRIGGERs in mysql and other database backend. Also I am familiar with signals in django but those can not fit in my needs. (because database event is somewhat outside of django and have problems; with signals although it seems this is impossible!)


Solution

  • You could use schedule, it's very easy to apply for your problem.

    import schedule
    import time
    
    
    def job():
        print("I'm working...")
    
    
    schedule.every().hour.do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(1) 
    

    Here there is a thread where it is shown how to execute a task periodically. Then you could add some conditions to fit your scenario.