为什么这个APScheduler代码不起作用?

时间:2016-10-15 20:11:35

标签: python apscheduler

一直在寻找答案,所以我转向这里!它给了我错误,"无效索引"对于sched.start()!

import random
import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
import smtplib
import email


def randEmail():
    #Gets randLine
    file_object = open("lyrics.txt", "r")
    randLine = random.randint(1, 10)
    for i, line in enumerate(file_object):
        if i == randLine:
            break
    #line = randomly generated line
    file_object.close()

    #Email
    emails = [ 'emails']


    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login('login', 'password')
    server.sendmail('login',emails, line)
    server.quit()

    #Prints to notepad saying completed
    Date = datetime.datetime.now()


    with open("Server_Quit.txt", "r+") as ServerQuit:
        ServerQuit.write("Server has quit at " + str(Date))
    ServerQuit.close()


#Unsure whether working
#sched.Scheduler()
#sched.start()
#sched.add_interval_job(randEmail, hours=24, start_date='2016-10-10 18:30')

sched = BlockingScheduler()
@sched.randEmail('cron', day_of_week='mon-fri', hour=18, minutes=30)
sched.start()

我感谢任何帮助!我已经尽力让自己完成这项工作,并且自己解决了所有其他问题,但无法实现这一目标。另外,如果我想让它在我的电脑上运行并且每天都这样做,我可以将它添加到启动过程中,当我启动电脑时,调度程序将启动吗?

1 个答案:

答案 0 :(得分:0)

您可以通过使用scheduled_job装饰器修饰函数来将作业添加到调度程序中:

from apscheduler.schedulers.blocking import BlockingScheduler

sched = BlockingScheduler()

# minute=30 not minutes=30
@sched.scheduled_job('cron', day_of_week='mon-fri', hour=18, minute=30)
def randEmail():
    #Gets randLine
    with open("lyrics.txt", "r") as file_object:
        randLine = random.randint(1, 10)
        for i, line in enumerate(file_object):
            if i == randLine:
                break
    #line = randomly generated line

    #Email
    emails = [ 'emails']

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login('login', 'password')
    server.sendmail('login', emails, line)
    server.quit()

    #Prints to notepad saying completed
    Date = datetime.datetime.now()

    # You don't have to close the file if you use the with statement
    with open("Server_Quit.txt", "r+") as ServerQuit:
        ServerQuit.write("Server has quit at " + str(Date))

sched.start()

您还可以使用add_job方法:

sched.add_job(randEmail, 'cron', day_of_week='mon-fri', hour=18, minute=30)
sched.start()

我无法理解为什么它不能用作启动过程。