How to send a message to a recipient every x minutes by using python-xmpp (and gtalk)?

689 Views Asked by At
def message_received(connect_object, message_node):
    // if x event happens:
    exit()

jid = xmpp.JID(user)
connection = xmpp.Client(jid.getDomain(), debug=[])
connection.connect(server)
result = connection.auth(jid.getNode(), password, "qwerty")

connection.RegisterHandler('message', message_received)
connection.sendInitPresence()

while connection.Process(1):
    pass

Irrespective of what the above code does, I want to keep sending a message to a recipient once every hour as a reminder for something. Even if a message is received and the control goes to the message_received function, the message to be sent every hour should continue unless exit() was encountered.

Where do I insert the message? I want to use time.sleep() but any other solution is also acceptable.

1

There are 1 best solutions below

0
bmhkim On

If you're okay with using another utility to do this, I would prefer to use another tool (e.g., cron/anacron for *nixes) to run a short script that exits quickly and sends the message.

This method has some benefits:

  • Allows you to disregard execution time. If you use time.sleep(), in order to prevent drift when your messages go out (say the XMPP server is down for a day, and that 60 second or whatever timeout adds up to 24 minutes, your messages will start going out closer to the bottom of the hour than the top), you really should time your execution then subtract that from your sleep time. This adds code complexity, which requires more debugging.
  • Allows you to not worry about keeping the process alive. If your script were to spuriously hit a network error and crash, it'll automatically kick off again in an hour.
  • Uses a time tested and battle-proven mechanism for running jobs when you want them to be run.

Edit: I missed the need to halt on 'exit' command. If you use crontab, you can use python-crontab to automatically insert/remove the crontab entry for this job.