Just a user
Just a user

Reputation: 47

Programming time in Python

I want to program time that is independent and runs by itself in the background and ticks every second, and automatically changes Date every 24 seconds (1 second = 1 hour)

def PrintTime():
    D = 1
    M = 1
    Y = 2019
    print(D,"/",M,"/",Y)
    Time = 0
    while Time < 24:
        Time += 1
        time.sleep(1)
        if Time == 24:
            Time = 0
            D += 1
            M += 1
            if M in list[2,4,6,9,11] and D > 30:
                D = 1
            if M in list[1,3,5,7,8,10,12] and D > 31:
                D = 1
            if M > 12:
                M = 1
                Y += 1

This is the idea I had in mind, but the problem with this is the whole program would be sleeping every second, which is what I don't want to happen. Instead I want to run this by itself, in the background, without bothering the rest of the program.

Upvotes: 0

Views: 38

Answers (1)

rocksportrocker
rocksportrocker

Reputation: 7419

You can use the threading module to start a thread running your function with other code simultaneously. For example like this:

import threading
import time


def PrintTime():
    D = 1
    M = 1
    Y = 2019
    print(D, "/", M, "/", Y)
    Time = 0
    while Time < 24:
        print("Background thread: Time=", Time)
        Time += 1
        time.sleep(1)
        if Time == 24:
            Time = 0
            D += 1
            M += 1
            if M in list[2, 4, 6, 9, 11] and D > 30:
                D = 1
            if M in list[1, 3, 5, 7, 8, 10, 12] and D > 31:
                D = 1
            if M > 12:
                M = 1


thread = threading.Thread(target=PrintTime)
thread.start()

for i in range(10):
    print("do sth else", i)
    time.sleep(.7)

Upvotes: 1

Related Questions