If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

Web2py Cron

 

Web2py comes with a built-in cron to run schedule time the same idea of Unix cron.

http://web2py.com/books/default/chapter/29/4#Cron

 

However, the documentation lacks a simple example to follow, so here I give you a very basic one. :-)

 

Let's add a Python script to run every minute, so add this to your application crontab:

 

# please fix the path of your script, basically put your application name

0-59/1  *  *  *  * root *applications/instore/modules/background_updater.py

 

Add in your application a file background_updater.py inside the modules folder, where is the file isn't important. 

 

# File: background_updater.py

 

import time
def main():
    print 'Checking for updates...'
    time.sleep(5)
    # Do what ever you want to do in python
    # long duration HTTP requests
    # FTP Access, download to local, untar, unzip, copy, move,
    # In this poor example, just sleeping for 5 seconds
    print 'Updated finished! :-)'
if __name__ == '__main__':
    main()
 
 
If you want to have access to your Web2py global vars, like your models and controllers, just do as the exampe and start the path of your script with a *.
 
To check it running:
 
Enable the loggin.conf in your Web2py instance, copying the file logging.example.conf to logging.conf.
 
Configure the logging to be more verbose in the cron:
 
Change this line:
[loggers]
keys=root,rocket,markdown,web2py,rewrite,app,welcome
To:
[loggers]
keys=root,rocket,markdown,web2py,rewrite,app,welcome,web2py.cron
 
Add the following lines after to "[logger_web2py]" section.
[logger_web2py.cron]
level=DEBUG
handlers=consoleHandler
qualname=web2py.cron
propagate=0
 
In the section "[handler_consoleHandler]" change the level to:
level=DEBUG
 
Start your web2py server in the console and watch the cron dance. Enjoy!
 
 
NOTE:
Original recipe bu Luciano Pacheco (lucmult) posted on Movu.ca http://movu.ca/demo/article/show/31/web2py-cron-task

Related slices

Comments (2)

  • Login to post



  • 0
    simakwm 12 years ago

    If the script requires an argument like:

    0-59/1  *  *  *  * root *applications/instore/modules/background_updater.py --status

    web2py gives me a funny error:

    invalid application name: instore/applications/instore/modules/background_updater.py

    (Notice the the repeated application name) 

    Does it support parameters the way I mentioned?


  • 0
    web2pyslices 12 years ago

     

    Book quote: "...If you use two asterisks (**), the MODELs will not be executed. This is the recommended way of calling, as it has less overhead and avoids potential locking problems. ..."

    This approach should be used for enhancing the task's performance (if you are not doing db update in background of course)

    (commented by spametki)

     


Hosting graciously provided by:
Python Anywhere