skip to Main Content

fairly new to python and I’ve managed to iron out any wrinkles I’ve overcome before. However, I’m stuck when it comes to this. I need to run a script I’m writing on Parallels Desktop since I cannot use the MetaTrader 5 python library on my Macbook’s VS Code for an algo I’m writing.

The issue I’ve come across is that I need to run a certain section of the script once every 5th minute and so I am using the following code to trigger this.

import time

while True:
    if time.time() % (60 * 5) == 0:
        print(time.strftime('%H:%M:%S %Y-%m-%d', time.gmtime(time.time())))  #code 

I want triggered follows…

The code works with no issues on my Mac’s VSCode but when I run it on Parallel’s Desktop VScode, there is no output. No error either.

Is there any reason for this and how might I overcome this?

Thank you guys it’s been eating at me for a while.

2

Answers


  1. I see multiple sources why the code above code be problematic.
    If you take a look at:

    print(time.time())
    #output
    1677345971.6591382
    

    Everything behind the decimal separator . is a very small proportion of a second (unit microsecond and below).

    If you try time.time() % (60 * 5) == 0 the chance of hitting a time.time() that looks like 1677345971.00000000 is minimal since your code wont be triggered at that exact microsecond.

    But only in that case time.time() % (60 * 5) == 0 would be true since no microseconds are left in your modulus calculation.

    I don’t know why it works on your mac but i guess it is because your mac is not using float to show time.time().

    In your case you coult try to use the following code:

    if int(time.time()) % (60 * 5) == 0:
    

    This turns your time from 1677345971.6591382 into 1677345971 where the unit is seconds. Now your calculation int(time.time()) % (60 * 5) == 0 can be fulfilled not only by chance of leaving 0 microseconds behind.

    Login or Signup to reply.
  2. I think @tetris programming said the right thing about some inevitable mistakes in your code. However, it will repeat print() many times in that second.

    I have provided the following code to help you better achieve your original purpose. Use the schedule package by command pip install schedule, which is a module for executing tasks on a regular basis.

    import schedule
    import time
    
    def run():
        print(time.strftime('%H:%M:%S %Y-%m-%d', time.gmtime(time.time())))  #code 
    
    schedule.every(5).minutes.do(run)
    
    while True:
        schedule.run_pending()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search