Lachlan
Lachlan

Reputation: 1282

Python: Do something then sleep, repeat

I'm using a little app for Python called Pythonista which allows me to change text colour on things every few seconds. Here's an example of how I've been trying to go about doing this in an infinite loop;

while True:
    v['example'].text_color = 'red'
    time.sleep(0.5)
    v['example'].text_color = 'blue'
    time.sleep(0.5)
    # and so on..

The issue here is that this freezes my program because Python keeps sleeping over and over, and I never see any change. Is there a way of being able to see the change (the text changing to red/blue/etc) and then doing the next task x amount of time later, and so on?

Upvotes: 7

Views: 792

Answers (1)

AlexanderNajafi
AlexanderNajafi

Reputation: 1651

You will need to create a new thread that runs your code. Put your code in its own method some_function() and then start a new thread like this:

thread = Thread(target = some_function)
thread.start()

Upvotes: 2

Related Questions