简体   繁体   中英

Restarting Heroku Python script periodically

I made a Flask-Python web application that scrapes the fixture of Real Madrid and displays it in a neat countdown page. I am trying to host it via Heroku . i moved the scraping part to the main python script and passed the scraped variables via render_template .

My question is how does the Python script run on the Heroku servers? Is it called when someone opens the webpage or does it run only once and serves the requests? If it is like that is there a way to restart the servers or rerun the Python script periodically so the changes in fixtures is reflected in the webpage.

Here is my app.py

import requests
import datetime
from bs4 import BeautifulSoup as bs
from lxml import html
url = 'http://www.realmadrid.com/en/football/schedule'
response = requests.get(url)
html = response.content
soup = bs(html)
loc = soup.find('p', {'class': 'm_highlighted_next_game_location'}).contents
loc1 = loc[0]
if "Santiago" in loc1:
    opp = soup.find('div',{'class':'m_highlighted_next_game_team m_highlighted_next_game_second_team'}).strong.contents
else:
    opp = soup.find('div', {'class': 'm_highlighted_next_game_team'}).strong.contents
opp1=opp[0]
time = soup.find('div', {'class': 'm_highlighted_next_game_info_wrapper'}).time.contents
time1 = time[0]
date = soup.find('header', {'class': 'm_highlighted_next_game_header'}).time.contents
date1 = date[0]
times = time1.split(":")
dates = date1.split("/")

hour = times[0]
mintemp = times[1]
minutes = mintemp[:-2]
year = dates[0]
month = dates[1]
day = dates[2]

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html',hour=hour,minutes=minutes,year=year,month=month,day=day,loc=loc1,opp=opp1)

if __name__ == '__main__':
    app.run(debug=True)

PS : I'm using Heroku for the first time. Please excuse if something sounds stupid.

Heroku is considered 'lazy' and stops servers if they have been idle for more than 30 minutes (also to save power). However, if your app makes a request, it will awaken right up (might take a couple of seconds to wake up). In your case, it will rerun the python script every-time the website is opened and a request is made.

If you want to update fixtures periodically without making a request from your website, check out Heroku Scheduler , which lets you schedule heroku tasks periodically. Keep in mind that you need to let the heroku server sleep for at least 6 hours/day for the free version.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM