Home > Mobile >  Execute a Command once a Week in Python
Execute a Command once a Week in Python

Time:07-12

I have a script for a Twitter bot which will send out a Tweet every Friday, however I'm struggling to find a way to make keep it from killing the code if it is not Friday.

I have tried using a loop which does usually work for my Discord bot, but my 11pm brain didn't realise it was discord.py syntax until before I executed that. As a result, I can't think of anything else to try. I have looked over Google and the links to this site that Google gives but I can't find much that helps me.

Here is the code I am using:

for i in range(10000):
  if date.today().weekday() == 6:
    i  = 1
    print("Congratulating those who made it to Friday :D")
    api.update_status(f"Week {i} of Congratulations Sailor, you made it to Friday!\nhttps://www.youtube.com/videoid")
    print("Congratulated\n")
  else:
    print("not friday :(")
    asyncio.sleep(10)

But that just constantly prints not friday :( into the console for 10 seconds before killing the code and not trying again.

So any help would be appreciated. Also, I am sorry if I am missing something so simple, my 11pm brain isn't the best.

Thanks

CodePudding user response:

You can use the schedule module to schedule a job to run once a week. Schedule is a light-weight in-process scheduler for periodic jobs in Python.

import time
import schedule

def job():
    print("I'm working...")
    # add your Twitter code here

# Run job on a specific day of the week
schedule.every().friday.do(job)

# Run job on a specific day of the week and time
schedule.every().friday.at("13:15").do(job)

while True:
    schedule.run_pending()
    time.sleep(1800)

More examples are found here.

Alternatively, rather than running a Python process 24x7, you could use the native scheduler to run your application. On Windows search for "Task Scheduler" and for both macOS and Linux a cron job can be specified. Python executes with your script on your specified schedule then terminates when the application is done.

CodePudding user response:

Not sure if it helps but you could try using the time module. It has a sleep function, and you could perhaps make it sleep for a day.

There are a few issues with using sleep for a long time since sleep(n) doesn't sleep exactly for n seconds, it could sleep for a slightly shorter time. Hard coding it using the time function might be useful if that happens.

  • Related