Keep counting down also when the program is not running

mR-Jacaj :

I recently opened another Q about different thing, and now I want to keep count down the time also when the program is not running, I think I know how to do this, maybe calculate how much time is remaining and then minus it with the current time, but I'm not sure, so this is why I'm asking here.

Is there a way to keep calculate the time also when the program is not running, for example, I'm counting down from 60 , closing the program, and then when I open it i will see 45 seconds (15 seconds).

I want to write the time into a file and then reading from it.

Current Program

import os
from time import sleep

class CountDown:
    def __init__(self):
        if not os.path.exists('last_time.txt'):
            with open('last_time.txt', 'w') as f:
                pass
        self.write_time()

    def countdown(self, time=60) -> None:
        while time > 0:
            print(time)
            sleep(1)
            time -= 1
            f = open("last_time.txt", 'w')
            f.write(str(time))
            f.close()

    def write_time(self) -> None:
        with open('last_time.txt', 'r') as f:
            if not os.stat('last_time.txt').st_size == 0: # Check if file is empty
                self.countdown(int(f.read()))
            else:
                self.countdown()

if __name__ == '__main__':
    CountDown()
Ed Ward :

This should work:

import time, os

endtime = 0
def setup(n=60):
    global endtime
    if os.path.isfile("time.txt"):
        with open("time.txt") as f:
            endtime = float(f.read())

        if time.time() > endtime:
            delfile()
        else:
            return
    with open("time.txt","w") as f:
        endtime = time.time()+n
        f.write(str(endtime))

def delfile():
    os.remove("time.txt")

print("Starting timer... ", end="")
setup()
print("Done!")

while True:
    print("Time remaining:", round(endtime-time.time()))
    time.sleep(1)
    if time.time() > endtime:
        break

delfile()

Sample session:

Starting timer... Done!
Time remaining: 60
Time remaining: 59
Time remaining: 58
Time remaining: 57
Time remaining: 56
Traceback (most recent call last):
  File "...", line 27, in <module>
    time.sleep(1)
KeyboardInterrupt

--- RESTART ---

Starting timer... Done!
Time remaining: 45
Time remaining: 44
Time remaining: 43
Time remaining: 42
Time remaining: 40
Time remaining: 39

...

If you want to use a class, use this:

import os, time

class CountDown:
    def __init__(self, n=60):
        self.endtime = 0
        self.setup(n)

    def setup(self, n):
        if os.path.isfile("end_time.txt"):
            with open("end_time.txt") as f:
                self.endtime = float(f.read())

            if time.time() > self.endtime:
                self.delfile()
            else:
                return
        with open("end_time.txt","w") as f:
            self.endtime = time.time()+n
            f.write(str(self.endtime))

    def countdown(self) -> None:
        while True:
            print("Time remaining:", round(self.endtime-time.time()))
            time.sleep(1)
            if time.time() > self.endtime:
                break
        self.delfile()

    def delfile(self):
        os.remove("time.txt")

if __name__ == '__main__':
    c = CountDown(60)
    c.countdown()

Explanation:

When you create an instance of this class, it tries to load the file. This file will contain a timestamp of when the timer will end. If the file doesn't exist, or that timestamp has already passed, it writes a new timestamp - a minute in the future - to the file. It stores the end-time as an attribute. When you call countdown(), it prints the difference in time between the current time, and the end time, until the end time has passed, at which point it deletes the file.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16632&siteId=1