Run Console Command Only When Users Logged In?

Hi folks,

I currently have a system with a console command working in the background, being initiated by crontab at regular intervals.

I was just wondering if there is any way to control the running of the command so that it only runs when there are users logged in? I think this might be more of a PHP question but I thought I would ask it here anyway to get people’s thoughts on it.

I am just brainstorming here, anything is possible it is just a question of required effort.

First you need to track when users are logged on, logins are generally maintained in session state when using Yii. PHP sessions are normally encoded using an internal PHP function so you can’t really iterate through them and find valid logins.

So you will need to store a last refresh time or similar data against the user record, using your login expiry time you can work out roughly if users are “logged in”, note this doesn’t account for those who hit the logout link and you can’t really track those because if you raise a flag they could still be logged in on a another machine with a different session.

Now using your cron script figure out using the above data if any valid logins exist and terminate if not.

Thanks for your input.

From digging about on google a bit, it seems that you can’t interate PHP sessions data - you can only access the session data specific to your login.

So it would seem that database logging would be required to store login and logout times for each session. If there is a session that is not logged out, the script called by crontab can see there is a user logged in and run the rest of the script.

As I am not really well-versed with sessions, can someone tell me if there is way to guarantee a user gets logged out when their session ends? Or is there a risk of sessions being destroyed without a proper session-destroy routine (with the assumption that the db can only be updated on session-destroy)?