簡體   English   中英

如何讓我的腳本在 Windows 上使用 python 每 30 分鍾重復一次

[英]how to get my script to repeat every 30 mins with python on windows

我有下面的腳本,我希望它每 30 分鍾運行一次,有人能指出我如何做到這一點的正確方向。

我已經搜索了這樣的現有問題,但似乎沒有找到任何適用於我的腳本的想法,但不知道這是否是我愚蠢。

我的腳本在我的屏幕上點擊不同的位置,然后進行屏幕截圖,然后將圖像發送到我的 gmail 帳戶。

import pyautogui
import time
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os


time.sleep(5)
pyautogui.PAUSE = 1
pyautogui.moveTo(922,134)
pyautogui.click()
pyautogui.PAUSE = 1
pyautogui.moveTo(178,277)
pyautogui.click()
pyautogui.PAUSE = 1
pyautogui.moveTo(178,297)
pyautogui.click()
pyautogui.PAUSE = 1
pyautogui.moveTo(178,315)
pyautogui.click()
pyautogui.PAUSE = 1
pyautogui.screenshot('web.png')

pyautogui.PAUSE = 5

gmail_user = "user@gmail.com"
gmail_pwd = "password"

to = "user@gmail.com"
subject = "Report"
text = "Picture report"
attach = 'web.png'

msg = MIMEMultipart()

msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject

msg.attach(MIMEText(text))

part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
   'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)

mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()

使用 windows schtasks:

schtasks /create /sc minute /mo 30 /tn "PyAutoGUI Task" /tr "python <path to script>"

您的循環應如下所示:

while '1' == '1':
    '''
    Your script that should loop here
    '''
    time.sleep(1800)

讓我們假設原始腳本的文件名是 testfile.py

使用以下代碼在與第一個文件相同的目錄中創建另一個文件:

import time,os
while 1:
    time.sleep(1800)
    os.system("start python testfile.py")

無論腳本運行需要多長時間,運行此腳本都會每 30 分鍾運行一次您的其他文件!

  1. 包裝程序(如果需要,請確保通過設置環境變量來提供憑據)
  2. 創建一個批處理文件,命令處理器運行 python 程序
  3. Windows Scheduler 中創建任務以觸​​發批處理文件

我相信 time.sleep(),如其余答案所述,即使在不使用時也會占用處理器。

我有一個類似的要求,我必須運行一段代碼,但也要每 30 分鍾連接一次服務器,否則它會超時。

這就是我所做的

import time
start = time.time()
process_time = 0
max_processing_time = 20000
sleep_time = 1800

while process_time < max_processing_time:
    if (time.time() - start) > sleep_time:
        start = time.time()
        service = service_connect() ## Connect to server every 30 minutes
    
    ## Otherwise keep on running this code
    function_which_I_want_to_run_continously()

在您的場景中,您可以在“if”塊中插入您的代碼段。 您可以根據需要設置max_processing_timesleep_time

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM