Search code examples
pythonschedulepyautogui

pyautogui and schedule are not working together


I'm writing a program that presses a key every 10 seconds. To do this, I am using a combination of pyautogui and schedule.

from pyautogui import press, typewrite, hotkey
import schedule

keystroke = "w"

def keypress():
    press(keystroke)
schedule.every(10).seconds.do(keypress)

But when I run this, nothing happens. I wait 10 seconds, but no key gets typed. What am I doing wrong?


Solution

  • Let's go over your code section by section to see if we can identify what the problem is.

    • You import some libraries
    • You define a function that you'd like to run every 10 seconds
    • You tell the default scheduler that you want to call your function every 10 seconds
    • Then your program terminates

    There are two somewhat related problems:

    • Nowhere in the code do you tell the scheduler to run any scheduled jobs
    • Your code instantly terminates before any scheduled jobs are run

    To fix these you need your program to loop and have the scheduler check for and run any pending jobs.

    The following code defines a simple job, and schedules it to run every 10 seconds. Then it loops forever checking for pending jobs every second.

    import schedule
    import time
    
    def job():
        print("Running....")
    
    schedule.every(10).seconds.do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    If all you want your program to do is loop and execute 1 action every n units of time the schedule module is overkill. It's more intended for complex systems where there are a large number of scheduled actions that all run on different cycles.