launching a method every x minutes

Hi all.

I browsed to forum but couldn’t find anything on that subject. Here is my proble : I need to listen to a data source every x minutes. The data source (a simple table in a database) is uploaded every X minutes by another script. With the data collected, I want to create objects in Panda3D, etc etc…

How can I create a function or a method that will be launched every X minutes ?

Hi,

There are two possible solutions. 
  • To create a task that internally counts the time elapsed and every N
    minutes do what you want.
    Something like (not tested).
from direct.task import Task

counter = 0

def exampleTask(task):
  counter += (counter + task.time)
  if counter > (N minutes * 60):
    print "Checking database"
    counter = 0
 
  return Task.done
  • To use a do-later task and to reprogrammate it at the end because
    it will be executed only one time.

    Something like (again, not tested):

  taskMgr.doMethodLater((N minutes * 60), myFunction, 'Task Name')

  def myFunction:
      print "Checking database"

      taskMgr.doMethodLater((N minutes * 60), myFunction, 'Task Name')

Regards.
Alberto

I use a task in my myasterserver to check if the game servers are still alive and update the sql DB every 10 minutes (600 seconds)

It looks like this:

import time

self.tmpTime=0

def controlTask(self, task):

        if (time.time() >= self.tmpTime):
            self.tmpTime = time.time()+600
            print "Checking Servers"
            self.refreshServers()
        return Task.cont

I’m using the system time to determine if 10 minutes have passed, though you could also do it with the task time.
Anyway, this method is proved to work properly.
The format of the system time (time.time() ) is in Unix time (that is the time in seconds since the first Unix was born -somewhere back in the 1970ies)

Another way would be to use the code ThomasEgi has posted yesterday:

https://discourse.panda3d.org/viewtopic.php?p=14220#14220

This way you would not need to check/increment anything each frame.

enn0x

Thanks everyone ! I asked my question on IRc and thomasEgi answered me. And I already did what I wanted to do with his method. Sorry to have forgot to say that my problem is solved.

Just a small precision : TE said that with his method, the method is executed every x seconds. It’s not true. What really happens is that there is x seconds between the end of a call and the beginning of the second one. Depending on the method it can be very different.

So this is a little late, but I thought I’d chime in anyway with yet another solution, probably a bit more “correct” than the one posted by ThomasEgi.

Try this:

def myPeriodicFunc(task):
    print '60 seconds have elapsed'
    return task.again

taskMgr.doMethodLater(60, myPeriodicFunc, 'myPeriodicFunc')