Search code examples
pythondcomapscheduler

APScheduler and Unmarshallable Objects


I would like to execute a function every second. I used the APScheduler and it works fine. However, there's a great performance penalty due to the fact that during each job I recreate the object which handles the connection to a server. I would like to create this connection object only once in the main thread and then pass it and reuse it when jobs are triggered. Problem is the connection object uses DCOM and I get unmarshallable object error.

I also tested an infinite loop approach combined with a sleep function but I noticed time drifting in this case. However, I create the DCOM object only once and performance wise looks a lot better.

Is there a workaround the unmarshallable object error and continue using APScheduler? Or, if this is not possible: How do I get rid of the time drifting issue in the infinite loop approach?


Solution

  • I solved the issue by using threading.Event and keeping the client in the main thread:

    import threading
    from apscheduler.scheduler import Scheduler
    import logging
    
    # Start the scheduler
    logging.basicConfig()
    sched = Scheduler()
    sched.start()
    
    ev = threading.Event()
    
    # Schedule job_function
    sched.add_interval_job(job, Ts, args=[ev])
    
    while True:
        ev.wait()
        # do stuff with the unmarshallable object
    
        ev.clear()
    
    def job(ev):
        ev.set()
    

    I haven't noticed time drifts with this approach.