How to enable maintenance mode only when there are no active users?
Solution 1 - Going Down:

Using the Going Down module (credits: J. Reynolds) could be a valid compromise (and maybe help to create a custom work around). Some more details about this module (from its project page):


  ... warns site visitors that the web site will be going down for maintenance at a specified time. The default configuration displays a fixed position red overlay message at the bottom of the browser window with text in the format 'Drupal is going offline for maintenance at Tue Feb 21 14:41:08 2012 -0800'. Module configuration is added to the Site Maintenance administration page (admin/settings/site-maintenance).


Here is a screenprint about it (also from its project page):



Only using this module will only reduce the risk of active users when you want to enable maintenance mode (though not completely reduce it).

However, by using that module, you may be able to use the Rules module to build some custom rule(s), in which you add your own custom Rules Conditions to go check if the time left for scheduled maintenance date/time is still sufficient.

Such Rules Condition would be to perform some custom PHP code, to retrieve the date/time set via the Going Down module. And then add this Rules Condition when visiting pages where you want to avoid your issue.

Solution 2 - Rules (and Message) is your friend:

Use the Rules module to create a custom rule that uses Rules Event "Drupal is initializing". Add whatever Rules Conditions you want, if any (eg: not for users with role admin). And add the appropriate Rules Action(s) to perform some type of special logging, e.g. using the Message module to create custom log data. Such log data should include things like timestamp, user id, current path, etc. If you'd use the Message module, you could create a (rather basic) view (using the Views module) to list the relevant log records that got created by this custom rule.

Enable this custom rule only X minutes (pick whatever value that fits for X) before you plan to enable maintenance mode. From then on just browse the views results to get an idea about how long ago which user/visitor has been visiting which path. For any events (log records) longer then Y minutes ago, just assume that user/session is not really doing anything on the site anymore at the moment you're browsing your Views result.