Freddy
Freddy

Reputation: 1

Python: Ending a Time-Based Loop after X Seconds

My Code is supposed to LeftMouse lick every "y" seconds on a set position on the screen which is working fine:

import pyautogui

def autoclick():
 threading.Timer(0.1, autoclick).start()
 pyautogui.click(1230, 618)

Problem comes with ending the loop.

Im asking for a time:

ScriptTime = int(input("Type the time in Seconds the Script should run: "))

and then tried to tie "ScripTime" to a counter to end "autoclick ()"

import time

t_end = time.time() + 1 * ScriptTime
while time.time() < t_end:
    autoclick()

Im guessing it hast to do with the usage of modules "Threading" and "Time", and those not communicating well. But I started Python yesterday, so help would be appreciated.

(There are no Errors put out durring execution, it just goes on forever and doesn't stop, and since my Mouse is locked, clicking on the screen, I can X out NOR use CTRL+C or ALT+F4, since im in a different window during execution.)

Upvotes: 0

Views: 343

Answers (1)

Poke
Poke

Reputation: 61

I think I see why it is going forever.

While attempting to import pyautogui raised an ImportError for me, I did import the threading module.

Here's the docstring from threading.timer:

Call a function after a specified number of seconds:

t = Timer(30.0, f, args=None, kwargs=None)
t.start()
t.cancel()     # stop the timer's action if it's still waiting

so the problem is (probably) that a single call to your autoclick function causes it to loop infinitely a THAT point, not in the while loop.

So, I'd recommend replacing your autoclick function with this:

def click():
    pyautogui.click(1230, 618)

def autoclick():
    threading.Timer(0.1, click).start()

or this:

def autoclick():
    threading.Timer(0.1, pyautogui.click, args=(1230, 618))

Aside: Where did you get the pyautogui module?

Nevermind; also, pip is a much more powerful tool than I realized.

Upvotes: 1

Related Questions