Search code examples
pythonloopscron

Simultaneous run of python loops from cron


I've a script with a loop for some minutes. It starts at 9:30AM and it runs a loop (time.sleep(120)) and then re-execute the script) for a variable amount of time (max 2h).

Now I would like to run a second script (at the same hour) which does the same: starts a loop for a variable amount of time.

Will the 2 loops conflict? Can I run 2 loops of python3 at the same time or I need any particular command to run them as different processes (like the & in bash)?


Solution

  • use the threading module. The following executes print_cube and print_square simultaneously.

    import threading 
      
    def print_cube(num): 
        """ 
        function to print cube of given num 
        """
        print("Cube: {}".format(num * num * num)) 
      
    def print_square(num): 
        """ 
        function to print square of given num 
        """
        print("Square: {}".format(num * num)) 
      
    if __name__ == "__main__": 
        # creating thread 
        t1 = threading.Thread(target=print_square, args=(10,)) 
        t2 = threading.Thread(target=print_cube, args=(10,)) 
      
        # starting thread 1 
        t1.start() 
        # starting thread 2 
        t2.start() 
      
        # wait until thread 1 is completely executed 
        t1.join() 
        # wait until thread 2 is completely executed 
        t2.join() 
      
        # both threads completely executed 
        print("Done!") 
    

    You can also use apscheduler, but it will run the processes separately.

    from apscheduler.scheduler import Scheduler
    
    # Start the scheduler
    sched = Scheduler()
    sched.start()
    
    # Schedule job_function to be called every two hours
    @sched.interval_schedule(hours=2)
    def job_function():
        print ("Hello World")
    
        time.sleep(120)
        print ("my second script")