Timing Issue with Neuromodulation Stimulus Using Threading

Hi PsychoPy experts,

I’m currently working on an experiment using PsychoPy and have run into a timing issue. In my setup, I have two types of stimuli:

  1. Stimulus 1: This stimulus triggers my device via PsychoPy’s parallel port component parallel.ParallelPort(address=0x378) for 10 seconds.
  2. Neuromodulation Stimulus: This one is more complex. It needs to start 6 seconds before Stimulus 1 and end 4 seconds after, totaling 20 seconds. However, rather than just switching on and off, this neuromodulation stimulus continuously receives keyboard input (‘s’) during its duration using a neuromodulation package (with the function keyboard.on_press()).
    def on_key_press(event):
        global counter
        if event.name == 's':
            counter += 1
            if counter in (1,2,3,4,5):
                myMagstim.fire()
            elif counter > 5:
                return
    def run_tms():
        counter = 0
        keyboard.on_press(on_key_press)
        time1 = time.time()

To handle the neuromodulation part, I implemented a separate thread to run it in parallel with the main experiment. Despite this, the timeline for the neuromodulation stimulus consistently triggers at the wrong times during actual runs.

 thr1 = threading.Thread(target=run_tms)
 thr1.start()

My question is: Does PsychoPy have any built-in functionality that can manage this type of parallel timing while accurately recording the timeline? Any advice or suggestions for a more reliable implementation would be greatly appreciated.

Thanks in advance for your help!

Best,
Xiaomin