Amy Gamble
Amy Gamble

Reputation: 175

Stopping a thread without loop (a function that takes a long time)

I'm writing a program that at 3AM, it reads everything from a file and downloads the files from the links one by one, and stops doing so (pauses the download) if it's 7AM

But my problem is If I use os.system("wget name") I won't be able to stop it, I can't put a flag in a while loop to check it because os.system() won't finish until the download is complete. I can't think of any other way. My net is unstable so I assume I have to use wget, I heard of urllib but I'm not sure if it will work with my unstable connection!

I'm planning on running this on ArchLinux on my raspberry Pi

Upvotes: 0

Views: 124

Answers (1)

tdelaney
tdelaney

Reputation: 77377

You have a subprocess you want to stop at 7 AM. Popen.wait has a timeout so all you have to do is figure out the timeout and use it.

import subprocess
import datetime
import time

now = datetime.datetime.now()
stopat = now.replace(hour=7, minute=0, second=0, microsecond=0)
delta = stopat.timestamp() - now.timestamp()
if delta > 0:
    proc = subprocess.Popen("wget name", shell=True)
    try:
        proc.wait(delta)
    except subprocess.TimeoutExpired:
        proc.terminate()
        try:
            proc.wait(2)
        except subprocess.TimeoutExpired:
            proc.kill()

Upvotes: 1

Related Questions