0

I've been trying for around half an hour now and just cant seem to wrap my head around what im doing wrong here. Working Code:

import threading
from time import sleep


def printX():
    threading.Timer(5.0, printX).start()
    print("five")


printX()
while True:
    print("1")
    sleep(1)

This works, however I need to be able to dynamically assign what the print statement will be along with the delay. Desired Code:

import threading
from time import sleep


def printX(time, message):
    threading.Timer(int(time), printX).start()
    print(str(message)


printX(time, message)
while True:
    print("Rest of the program continues")
    sleep(1)

Thanks for any help in advance :).

1
  • 1
    Use the args argument: threading.Timer(time, printX, args=(time, message)).start() - Commented Aug 22, 2018 at 5:10

2 Answers 2

1

threading.Timer could pass arguments with args:

threading.Timer(int(time), printX, (time, message)).start()

read more on its doc.

Sign up to request clarification or add additional context in comments.

Comments

1

An alternative method is to define a class with printX as an inner function.

class thread:

    def __init__(self, time, message):
        self.time = time
        self.message = message

    def printX(self):
        threading.Timer(int(self.time), self.printX).start()
        print(str(self.message))

thread(3,"test message").printX()

while True:
    print("Rest of the program continues")
    sleep(1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.