【发布时间】:2021-06-14 00:16:05
【问题描述】:
我有一个关于我最近开发的 React 应用程序的问题。它基本上是一个登陆页面,它使用 React 前端和 Node+Express 后端,并从各个页面抓取数据(抓取器是用 Python 开发的)。
目前,React 应用程序本身托管在 Heroku 中,并且爬虫的执行正在运行,但它不是自动安排的。 当前设置如下:
- 用于 Python 爬虫的 EC2
- AWS RDS MYSQL 用于数据库,我将数据从 EC2 抓取工具写入其中
我创建了一个单独的文件来执行所有其他爬虫。
main.py
import time
import schedule
import os
from pathlib import Path
print('python script executed')
# make sure, what is the current working directory to add the right paths to scrapers
path = os.getcwd()
print(path)
#exec(open("/home/ec2-user/testing_python/lhvscraper.py").read())
filenames = [
#output table: fundsdata
Path("/home/ec2-user/testing_python/lhvscraper.py"),
Path("/home/ec2-user/testing_python/luminorscrapertest.py"),
Path("/home/ec2-user/testing_python/sebscraper.py"),
Path("/home/ec2-user/testing_python/swedscraper.py"),
Path("/home/ec2-user/testing_python/tulevascraper.py"),
#output table: feesdata
Path("/home/ec2-user/testing_python/feesscraper.py"),
#output table: yield_y1_data
Path("/home/ec2-user/testing_python/yield_1y_scraper.py"),
#output table: navdata
#Path("/home/ec2-user/testing_python/navscraper.py"),
]
def main_scraper_scheduler():
print("scheduler is working")
for filename in filenames:
print(filename)
with open(filename) as infile:
exec(infile.read())
time.sleep(11)
schedule.every(10).seconds.do(main_scraper_scheduler)
while True:
schedule.run_pending()
time.sleep(1)
我已经成功建立了MYSQL和EC2之间的连接,并在Putty上进行了测试-
这意味着,如果我执行我的 main.py,所有的抓取工具都在工作,将新数据插入到 MYSQL 数据库表中,然后再次重复(参见上面的代码)。唯一的问题是,当我关闭 Putty(终止连接)时,main.py 函数将停止运行。
所以我的问题是:如何设置它,以便 main.py 文件始终继续运行(比如说,每天中午 12 点运行一次) ) 没有我执行?
我知道这是关于设置 cron 作业或调度程序(或类似的东西),但我现在没有设法设置它,所以非常需要你的帮助。
提前致谢!
【问题讨论】:
-
多久一次?简单的方法是将您的脚本添加到
/etc/cron.hourly或/etc/cron.daily。如果它需要不同的时间表,那么它只是使用crontab -e添加一行,但您需要知道该行的格式。man crontab可以帮忙。 -
@TimRoberts 编辑了这个问题。例如,假设每天中午 12 点进行一次。
-
您能否再解释一下:例如,如何设置这个
/etc/cron.daily?实际上这是我的主要问题,如何设置 crontab ... -
我会添加一个答案来解释。
标签: python mysql amazon-web-services cron scheduled-tasks