Schedule background tasks in Bluemix |
The trick is in the file manifest.yml and the Cloudfoundry documentation has all the needed details (Bluemix is built on this open standard). The attribute "no-route" is set to true, indicating that this is not a Web application and we don't need a subdomain name. In addition the attribute "command" is set to invoke the Python interpreter with my script as parameter. Basically, this starts my background task:
applications:
- name: hltimer
memory: 256M
instances: 1
no-route: true
command: python mytimer.py
path: .
The cron-like service script is pretty simple. It uses the "schedule" package to set up recurring jobs. I tested it with the Twilio API to send me SMS at given timestamps. You can also use it to scrape webpages in given intervals, kick off feed aggregators, read out sensors and update databases like Cloudant or DB2, and more. See this Github repository for the full source.
import schedule
import time
def job():
#put the task to execute here
def anotherJob():
#another task can be defined here
schedule.every(10).minutes.do(job)
schedule.every().day.at("10:30").do(anotherJob)
while True:
schedule.run_pending()
time.sleep(1)