Reputation: 4050
I have simple python script which I would like to host on Heroku and run it every 10 minutes using Heroku scheduler. So can someone explain me what I should type on the rake command at the scheduler and how I should change the Procfile of Heroku?
Upvotes: 36
Views: 34954
Reputation: 423
If you use free account [unverified*] on Heroku (so you cannot install addons), instead of using "Heroku scheduler", use time.sleep(n). You don't need Flask or any server in this case, just place script, say, inside folder Scripts (in default app/project by Heroku) and add to Procfile:
worker: python script.py
.
Of course you replace script.py with Path to your script, including name,
ex. worker: python Scripts/my_script.py
Note: If your script uses third-party modules, say bs4 or requests, you need to install them in pipenv install MODULE_NAME
or create requirements.txt
and place it where manage.py, Procfile, Pipfile, (etc) are. Next place in that requirements.txt:
requirements.txt
:
MODULE_NAME==MODULE_VERSION
You can check them in pip freeze | grep MODULE_NAME
Finally deploy to Heroku server using git
and run following command:
heroku ps:scale worker=1
That's it! Bot/Script is running, check it in logs:
heroku logs --tail
Source: https://github.com/michaelkrukov/heroku-python-script
unverified* - "To help with abuse prevention, provisioning an add-on requires account verification. If your account has not been verified, you will be directed to visit the verification site." It redirects to Credit Card info. However you can still have Free Acc, but you will not be able to use certain options for free users, such as installing addons:
https://devcenter.heroku.com/articles/getting-started-with-python#provision-add-ons
Upvotes: 32
Reputation: 33854
Sure, you need to do a few things:
Define a requirements.txt
file in the root of your project that lists your dependencies. This is what Heroku will use to 'detect' you're using a Python app.
In the Heroku scheduler addon, just define the command you need to run to launch your python script. It will likely be something like python myscript.py
.
Finally, you need to have some sort of web server that will listen on the proper Heroku PORT -- otherwise, Heroku will think your app isn't working and it will be in the 'crashed' state -- which isn't what you want. To satisfy this Heroku requirement, you can run a really simple Flask web server like this...
Code (server.py
):
from os import environ
from flask import Flask
app = Flask(__name__)
app.run(environ.get('PORT'))
Then, in your Procfile
, just say: web: python server.py
.
And that should just about do it =)
Upvotes: 44