You are not logged in.

#1 2018-07-22 09:30:07

leethaxor
Member
Registered: 2018-07-09
Posts: 31

[SOLVED] Python make one thread sleep whilst the others run?

I want to execute multiple functions and make them run separately but all the processes wait for the previous function to complete. This is a problem because, for example, backgroundLoader() in the code runs forever, so all functions after it will never run.

#!/usr/bin/env python
from multiprocessing import Process, Pool
from os import listdir, system
from os.path import isfile, join
from time import time, sleep
import random

def is_connected():
    try:
        # connect to the host -- tells us if the host is actually
        # reachable
        print('checking in 5 s....')
        sleep(5)
        create_connection(("www.duckduckgo.com", 80))
        return True
    except OSError:
        pass
    return False


def backgroundLoader():
    filesInDir = [f for f in listdir('/home/homee/Pictures/Backgrounds/') if isfile(join('/home/homee/Pictures/Backgrounds/', f))]

    totalFiles = 0

    fileArray = []

    for f in filesInDir:
        totalFiles += 1
        fileArray.append(f)

    while True:
        randInt = random.randrange(0, totalFiles, 1)
        system('feh --bg-scale /home/homee/Pictures/Backgrounds/' + fileArray[randInt])
        print('changed background')
        sleep(300)

def main():
    pBackground = Process(target=backgroundLoader(), args=())
    pNetwork = Process(target= is_connected(), args=())
    
    procs = []
    procs.append(pBackground)
    procs.append(pNetwork)

    for proc in procs:
        proc.start()


if __name == '__main__':
    main()

Last edited by leethaxor (2018-07-22 11:25:30)

Offline

#2 2018-07-22 10:24:43

Raynman
Member
Registered: 2011-10-22
Posts: 1,539

Re: [SOLVED] Python make one thread sleep whilst the others run?

You are running backgroundLoader() in the first line of main() instead of passing the function as the target.

Offline

#3 2018-07-22 11:24:51

leethaxor
Member
Registered: 2018-07-09
Posts: 31

Re: [SOLVED] Python make one thread sleep whilst the others run?

obs... thanks! Fixed the issue by removing the parentheses from target=function() <--

Last edited by leethaxor (2018-07-22 11:25:19)

Offline

Board footer

Powered by FluxBB