简体   繁体   English

每天远程运行一次 Python 脚本的最佳方法是什么

[英]What is the best way to remotely run a Python script once per day

I have a small 10 line python script that I want to run once per day at a certain time.我有一个小的 10 行 python 脚本,我想每天在某个时间运行一次。

I want to run it at 3am so I am thinking of running it remotely.我想在凌晨 3 点运行它,所以我想远程运行它。

At the moment I am looking at running an EC2 instance on AWS but it seems a little tedious for the task at hand.目前我正在考虑在 AWS 上运行 EC2 实例,但对于手头的任务来说似乎有点乏味。

Has anybody had similar experiences and if so, what was the best option for you.有没有人有类似的经历,如果有,对你来说最好的选择是什么。

I am using macOS.我正在使用 macOS。

You should use AWS Lambda which can be triggered using Cloudwatch, which can be scheduled using cron.您应该使用 AWS Lambda,它可以使用 Cloudwatch 触发,可以使用 cron 进行调度。 Check cloudwatch Rules.检查 cloudwatch 规则。 You can create a rule and then add trigger to lambda based on that.您可以创建一个规则,然后基于该规则向 lambda 添加触发器。 AWS Doc for the same . AWS Doc 用于相同的.

Another Option:另外一个选项:

If you still want to use an EC2, then use a micro instance to perform your task, add a cron job within your EC2.如果您仍想使用 EC2,则使用微型实例来执行您的任务,在您的 EC2 中添加一个 cron 作业。 Use EC2 instance scheduler for starting and stopping instances according to your need.根据需要使用 EC2 实例调度程序启动和停止实例。 So you'll use only EC2 when you need them.因此,您将仅在需要时使用 EC2。 See here for more AWS Doc for Automating Time-Based Elasticity .请参阅此处了解更多AWS Doc for Automating Time-Based Elasticity

If the script takes under 15 minutes to run, you could:如果脚本运行时间不到 15 分钟,您可以:

  • Create an AWS Lambda function with your script使用您的脚本创建AWS Lambda 函数
  • Configure an Amazon CloudWatch Event to trigger the Lambda function on a schedule配置Amazon CloudWatch 事件以按计划触发 Lambda 函数

See: Creating a CloudWatch Events Rule That Triggers on a Schedule - Amazon CloudWatch Events请参阅: 创建按计划触发的 CloudWatch Events 规则 - Amazon CloudWatch Events

You can run it once adding a time.sleep(86400) in a loop.您可以在循环中添加 time.sleep(86400) 一次运行它。 For example:例如:

import time
while True:
    your_basic_code
    time.sleep(86400)

This is a good solution if your code is not time consuming and you are not interested for time accuracy (if you are ok with 03:01 am for example for the 10th day, etc).如果您的代码不耗时并且您对时间准确性不感兴趣(如果您对上午 03:01 没问题,例如第 10 天等),这是一个很好的解决方案。 There are other solutions more accurate though, that will run the code exactly at 03:00不过,还有其他更准确的解决方案,它们将在 03:00 准确运行代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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