Zuss
Zuss

Reputation: 89

Setting a countdown timer for a function in Python

What I need is to set a countdown timer (for 2 minutes) for the first time initialize function is getting a callback (it will keep getting callbacks in the 2 min period). When 2 minutes end, reset the timer and do something else and when that ends by my "main" function wait for a new trigger from clipboard_monitor.on_text() in order to set again the countdown timer for the initialize function. Is this all possible?

Code:

import clipboard_monitor

class ABC():
  def __init__(self):
      .....
      
      .....
  def initialize(url):
      run = ABC()
      toDo.append(url)
      # What I ideally want is to print the message bellow with a counter of how many times this 
      # function has been called
      print("URL has been added to queue for download.")
      # For every element in the list.
      for x in toDo:
        # main() is another function I have that I am using what I got from the clipboard.
        run.main(x)
        # if the last element reached empty list and exit loop
        if x == toDo[-1]:
          toDo = [""]
          break
      .....
      
      .....
  def main(self, url):
      .....
      
      .....

clipboard_monitor.on_text(ABC.initialize)
clipboard_monitor.wait()

Thank you

Upvotes: 0

Views: 911

Answers (1)

patate1684
patate1684

Reputation: 649

you can use threading to do it like so :

#import clipboard_monitor
import threading

class ABC():
    def __init__(self):
        self.th = None
        self.url_list = []
      
      
    def initialize(self, url):
        if self.th is None:
            self.th = threading.Timer(120, self.timer_ended)
            self.th.start()
        
        self.url_list.append(url)
        print("URL has been added to queue for download. nb:" + str(len(self.url_list)))
        
    def timer_ended(self):
        self.th = None
        for x in self.url_list:
            self.deal_with_url(x)
        self.url_list = []

    def deal_with_url(self, url):
        print(url)

foo = ABC()
#clipboard_monitor.on_text(foo.initialize)
#clipboard_monitor.wait()

if we put this in python terminal and we test it with :

>>> foo.initialize("test1")
URL has been added to queue for download. nb:1
>>> foo.initialize("test2")
URL has been added to queue for download. nb:2
>>> foo.initialize("test3")
URL has been added to queue for download. nb:3
>>> foo.initialize("test4")
URL has been added to queue for download. nb:4
>>> test1
test2
test3
test4

test1 test2 test3 test4 is printed 120 seconds after the first call to initialize

Upvotes: 1

Related Questions