8

I would like my children to only use the computer for 30 minutes, at which time I would like the screen to be locked. At that point, if I choose to unlock the screen again, I would like the screen to lock again in another 30 minutes.

How can I write a script to do this?

2
  • @Serg at second thought, I don't think it is a dupe of that one. That question initially was to cycle breaks. I added the option to start counting time when a user actually starts working again, but it wasn' t part of the question. Jan 2, 2016 at 15:32
  • I can't post an answer on this closed question but lock-screen-timer will automatically lock the screen after X minutes which defaults to 30. Warning bubble messages are displayed at 30-15-10-5-3-2-1 minutes remaining with a system sound. See: askubuntu.com/questions/837078/… Mar 22, 2018 at 1:00

3 Answers 3

4

Run the script below in the background, and it will lock the screen after an arbitrary number of minutes:

The script

#!/usr/bin/env python3
import subprocess
import time
import sys

t = 0; max_t = int(sys.argv[1])

while True:
    # check runs once per minute
    time.sleep(60)
    # check the lock status, add 1 to current time if not locked, else t = 0
    try:
        subprocess.check_output(["pgrep", "-cf", "lockscreen-mode"]).decode("utf-8").strip()
        t = 0
    except subprocess.CalledProcessError:
        t += 1
    # if unlocked status time exceeds set time (in minutes), lock screen
    if t >= max_t:
        subprocess.Popen(["gnome-screensaver-command",  "-l"])
        t = 0

How to use

  • Copy the script into an empty file, save it as lock_screen.py
  • Test- run it from a terminal with the lock- time as an argument (minutes)

    python3 /path/to/lock_screen.py 30
    

    (Although for the test, I'd take a shorter time)

  • If all works fine, add it to Startup Applications Dash > Startup Applications > Add. Add the command:

    python3 /path/to/lock_screen.py 30
    
1
  • I understand everything that you've done and I like your solution. Thank you.
    – aam
    Jan 2, 2016 at 20:12
2

The script presented bellow starts upon user login and waits certain amount of time before locking the screen. Two caveats must be kept in mind: the script must be part of Startup Applications and it must be executable.

Time for each session can be configured within the script itself by changing TIME variable, according to /bin/sleep usage. From man sleep:

Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations that require NUMBER be an integer, here NUMBER may be an arbitrary floating point number.

The script can be started manually or as part of Startup Applications to be called upon each GUI login. Refer to How do I start applications automatically on login? for that.

Simple Setup

  1. Create folder named bin in your personal HOME folder.
  2. In bin folder create file named sessionLocker.sh. Copy the source code into that file
  3. Give executable permissions to the file by right clicking on it, go to Properties -> Permissions tab, check "Allow executing file as program" option. Alternatively, use chmod +x $HOME/bin/sessionLocker.sh in terminal
  4. Run Startup Applications. Add full path to script as one of startup applications. Example: /home/MYUSERNAME/bin/sessionLocker.sh
  5. Restat your Unity session to test.

The script is also posted on my personal github. Use git clone https://github.com/SergKolo/sergrep.git to download the source code.

Script Source

#!/bin/bash
##################################################
# AUTHOR: Serg Kolo 
# Date: Jan 2nd 2016
# Description: A script that locks session every x
#       minutes. 
# TESTED ON: 14.04.3 LTS, Trusty Tahr
# WRITTEN FOR: https://askubuntu.com/q/715721/295286
# Depends: qbus, dbus, Unity desktop
###################################################

# Copyright (c) 2016 Serg Kolo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal in 
# the Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 
# the Software, and to permit persons to whom the Software is furnished to do so, 
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all 
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


##############
# INTRODUCTION
##############

# This script locks user session every x minutes, and repeats this task
# upon user re-logging in. Useful for creating session for children, study session
# for college students, pomodoro sessions for self-learners ,etc.
#
# This can be started manually or as part of Startup Applications 

###########
# VARIABLES
###########
TIME="30m"

##########
# MAIN
##########
while [ 1 ]; 
do
  # Wait the time defined in VARIABLES part and lock the session
  /bin/sleep $TIME &&  qdbus  com.canonical.Unity /com/canonical/Unity/Session com.canonical.Unity.Session.Lock

  # Continuously query dbus every 0.25 seconds test whether session is locked
  # Once this sub-loop breaks, the main one can resume the wait and lock cycle.
  while [ $(qdbus  com.canonical.Unity /com/canonical/Unity/Session com.canonical.Unity.Session.IsLocked) == "true" ];
  do
    /bin/sleep 0.25 && continue
  done
done
8
  • I get the error: light-locker-command: command not found Jan 2, 2016 at 16:42
  • Fixed, replaced call to light-locker with a dbus method Jan 2, 2016 at 17:08
  • Works! +1 for dbus Jan 2, 2016 at 18:29
  • @JacobVlijm Something wrong with software because this answer shows 0 up and 0 down votes? Mar 22, 2018 at 0:56
  • @SergiyKolodyazhnyy +1 for VTC a question that you answered on :) Mar 22, 2018 at 0:57
-2

Thank you for the help. I decided to combine parts of your answer with other stuff I found online and came up with this solution in python 2.x:

import gobject, dbus, time, subprocess
from dbus.mainloop.glib import DBusGMainLoop  

time.sleep(30*60)
subprocess.Popen(["gnome-screensaver-command", "-l"])

def lock_status(bus, message):

    if message.get_member() != "EventEmitted": 
        return

    args = message.get_args_list()

    if args[0] == "desktop-unlock":  
        time.sleep(30*60)
        subprocess.Popen(["gnome-screensaver-command", "-l"])

DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.add_match_string("type='signal',interface='com.ubuntu.Upstart0_6'")
bus.add_message_filter(lock_status)
gobject.MainLoop().run()
1
  • Hi aam. Your answer messes with the system and edits your dconf database. The answer is bad because a.] I doubt if you actually understand what you are doing. b.] your solution cannot simply be turned on and off, nor can it easily be undone. You should at least add a warning to other users who might try your solution and get stuck with your setup, and provide a description on how to revert. -1 Jan 2, 2016 at 13:19

Not the answer you're looking for? Browse other questions tagged .