setInterval on the server

I want to set up a function to run when a user logs in and stop it running when they log out. I understand using accounts.onLogin/onLogout but where would I store the setInterval id so that I can access it when they log out?
Is there a best practice of how to access the setInterval returned id when I need it to clear the interval?

You could try using the Session. You could set it in the successful callback after their login on the client. Then check for it in the callback after a successful logout on the client.

One issue is you’ll also have to check if they disconnect (close their browser tab/window) - which is possible. Let me know if you need details.

Could you do you interval based on profile.online? Then you’d need one setInterval and fetch users where profile.online === true

Add a new field in your Users Collection called : interval_id.

  • onLogin : create interval and save the returned id in the user interval_id field.
  • onLogout : get the interval_id, clear the interval then delete it from the user.

For the hooks, you can use the user-status package, it provides a lot of hooks. (i’m on my mobile, can’t post the link now sorry).

This is not so easy. See here:

This seems like wrong approach to accomplish something.
What that function should do?
Why not just run global function all the time and modify it’s logged_users array property ?

In fact this seems to be the wrong approach to execute a periodic job.
It is preferable to use this package (Meteor-synced-cron), define your jobs and start them when needed and stop them when needed (with the hooks). With this package, the jobs can run on different servers and be controlled from anywhere.