Home > Back-end >  How to run multiple countdowns
How to run multiple countdowns

Time:02-26

I am working with multiprocessing in python and I can't figure out how to start a thread and continue the code.

The code should check if a new item has been added to a notepad file. If it is, it should wait 2 minutes and then delete it. I want this deletion process to be separate because in those 2 minutes more then one item can be added to the notepad file(that is done by another program I already wrote). Basically, for every new item that is added to the notepad file, I want to start a new thread which will delete the item after 2 minutes.

Here is what I have:

import time
import threading


a_file = open("file.txt", "r")

lines = a_file.readlines()
a_file.close()

a=len(lines)#the initial number of lines

n=0

def delete(a):#the function which deletes the new item 

    a_file = open("file.txt", "r")

    lines = a_file.readlines()
    a_file.close()

    del lines[a-1]# becasue of indexing it should delete the a-1 element in the list

    new_file = open("file.txt", "w ")

    for line in lines:
        new_file.write(line)

    new_file.close()
    a=a-1#decreases a so that the function isn't called again

while n==0:
    time.sleep(7)

    a_file = open("file.txt", "r")

    lines = a_file.readlines()
    a_file.close()

    b=len(lines)#the new number of lines 
    if b>a:
        a=b
        t1=threading.Thread(target=delete(a))#the thread 

Any help would be appreciated!

CodePudding user response:

Why not use Timers instead of using Threads?

Try running this, and see what it does:

from threading import Timer

def spong(what):
    print(what)

Timer(4.0, spong, args=("four point oh",)).start()
Timer(6.0, spong, args=("six point oh",)).start()
Timer(2.0, spong, args=("two point oh",)).start()
print("And, they're off!")
  • Related