当前位置: 首页>>技术教程>>正文


一个自动锁定屏幕以暂时脱离计算机的计时器?

, ,

问题描述

我正在寻找一个图形或命令行程序,它为我提供了以下工作流程:

  1. 开始25分钟的会议

  2. 25分钟后屏幕会自动锁定5分钟(或者可能只是变成黑色?)

  3. 现在我帮忙休息一下,因为除了看黑色或锁定屏幕外,我不能在电脑前做任何事情:)

  4. 5分钟后,屏幕自动返回,我可以继续工作

有没有一个程序正是这样做的?

最佳解决思路

一个完整的应用程序可能会有点过分;一个小小的后台脚本正在完成这项工作。

下面的脚本将在循环中完全按照您的提及进行操作:它将屏幕”normal”保持一段任意时间(以分钟为单位,您可以使用浮点数来部分设置分钟)并使屏幕变黑或将其向上翻转对于”breaktime”,你可以选择:)。

software-recommendation,lock-screen,ubuntu

要么:

software-recommendation,lock-screen,ubuntu


剧本

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

awaketime = int(float(sys.argv[1])*60)
sleeptime = int(float(sys.argv[2])*60)

def take_a_break():
    get = subprocess.check_output(["xrandr"]).decode("utf-8").split()
    screens = [get[i-1] for i in range(len(get)) if get[i] == "connected"]
    for scr in screens:
        # uncomment either one of the commands below [1]
        # darken the screen, or...
        subprocess.call(["xrandr", "--output", scr, "--brightness", "0"])
        # turn it upside down :)
        # subprocess.call(["xrandr", "--output", scr, "--rotate", "inverted"])
    time.sleep(sleeptime)
    for scr in screens:
        # back to "normal"
        subprocess.call(["xrandr", "--output", scr, "--brightness", "1"])
        subprocess.call(["xrandr", "--output", scr, "--rotate", "normal"])


while True:
    time.sleep(awaketime)
    take_a_break()

如何使用

  1. 将脚本复制到空文件中,将其另存为takeabreak.py

  2. 根据您的选择,取消注释第15行或第17行(如果您只是希望它使屏幕变暗,则可以跳过此步骤),如脚本中所示。

  3. 通过命令从终端测试运行脚本:

    python3 /path/to/takeabreak.py <uptime> <breaktime>
    

    例如:

    python3 /path/to/takeabreak.py 25 5
    

    每25分钟工作一次,休息5分钟

  4. 如果它符合您的要求,请将其添加到启动应用程序中:Dash>启动应用程序>添加命令:

    /bin/bash -c "sleep 15 && python3 /path/to/takeabreak.py 25 5"
    

EDIT

当然,你可以用任何你能想象的”dress up”脚本。在我脑海中浮现的第一件事就是一个小小的信息,通知你休息时间已经接近……

software-recommendation,lock-screen,ubuntu

代码

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

awaketime = int(float(sys.argv[1])*60)
sleeptime = int(float(sys.argv[2])*60)

message = "Break in 15 seconds"

def take_a_break():
    get = subprocess.check_output(["xrandr"]).decode("utf-8").split()
    screens = [get[i-1] for i in range(len(get)) if get[i] == "connected"]
    for scr in screens:
        # uncomment either one of the commands below [1]
        # darken the screen, or...
        subprocess.call(["xrandr", "--output", scr, "--brightness", "0"])
        # turn it upside down :)
        # subprocess.call(["xrandr", "--output", scr, "--rotate", "inverted"])
    time.sleep(sleeptime)
    for scr in screens:
        # back to "normal"
        subprocess.call(["xrandr", "--output", scr, "--brightness", "1"])
        subprocess.call(["xrandr", "--output", scr, "--rotate", "normal"])

while True:
    time.sleep(awaketime-15)
    subprocess.Popen(["notify-send", message])
    time.sleep(15)
    take_a_break()

编辑2

Unity的基本GUI元素

如注释中所述,在具有基本GUI功能的版本(设置)下方,切换脚本并更改正常运行时间/中断时间设置。如果您按照说明操作,设置非常简单:)

software-recommendation,lock-screen,ubuntu

配料:

  1. 两个脚本(下面进一步说明):

    • takeabrake_run是实际的脚本,取代了上面的脚本,

    • 正如预期的那样,takeabreak_gui是管理(时间)设置和编写脚本的脚本。

  2. 一个.desktop文件:

    [Desktop Entry]
    Type=Application
    Name=Take a Break
    Exec=takeabreak_gui toggle
    Icon=/path/to/takeabreak.png
    
    Actions=Toggle script;Change time settings;
    
    [Desktop Action Change time settings]
    Name=Change time settings
    Exec=takeabreak_gui timeset
    OnlyShowIn=Unity;
    
    [Desktop Action Toggle script]
    Name=Toggle script
    Exec=takeabreak_gui toggle
    OnlyShowIn=Unity;
    
  3. 和一个图标:(right-click>将图像保存为takeabreak.png)

    software-recommendation,lock-screen,ubuntu

如何设置

  1. 如果目前还不存在,则创建目录~/bin

  2. 注销/运行或运行source ~/.profile以“激活”$PATH~/bin的存在

  3. 将下面的两个脚本复制到两个空文件中,命名(确切)

    takeabreak_gui
    

    takeabreak_run
    

    (没有扩展!)并将它们保存在~/bin

  4. 使两个脚本都可执行(!)

  5. 将图标(right-click > save image as)复制到您的计算机。将其命名为(确切地)为takeabreak.png

  6. .desktop文件复制到空文件中。编辑线:

    Icon=/path/to/takeabreak.png
    

    并用真实路径替换图标的路径。

而已!

脚本:

  1. takeabreak_run

    #!/usr/bin/env python3
    import subprocess
    import sys
    import time
    
    awaketime = int(float(sys.argv[1])*60)
    sleeptime = int(float(sys.argv[2])*60)
    
    message = "Break in 15 seconds"
    
    def take_a_break():
        get = subprocess.check_output(["xrandr"]).decode("utf-8").split()
        screens = [get[i-1] for i in range(len(get)) if get[i] == "connected"]
        for scr in screens:
            # uncomment either one of the commands below [1]
            # darken the screen, or...
            subprocess.call(["xrandr", "--output", scr, "--brightness", "0"])
            # turn it upside down :)
            # subprocess.call(["xrandr", "--output", scr, "--rotate", "inverted"]); time.sleep(0.2)
        time.sleep(sleeptime)
        for scr in screens:
            # back to "normal"
            subprocess.call(["xrandr", "--output", scr, "--brightness", "1"]); time.sleep(0.2)
            subprocess.call(["xrandr", "--output", scr, "--rotate", "normal"]); time.sleep(0.2)
    
    while True:
        time.sleep(awaketime-15)
        subprocess.Popen(["notify-send", message])
        time.sleep(15)
        take_a_break()
    
  2. takeabreak_gui

    #!/usr/bin/env python3
    import os
    import subprocess
    import sys
    
    # define the settings file's location
    setting = os.environ["HOME"]+"/"+".time_setting"
    # default values (if no settinghs were made)
    default_up = "25"
    default_break = "5"
    
    arg = sys.argv[1]
    
    def check_running():
        # function to check if the script runs
        try:
            return subprocess.check_output(["pgrep", "-f", "takeabreak_run"]).decode("utf-8").strip()
        except subprocess.CalledProcessError:
            return False
    
    def start(uptime, breaktime):
        # function to start the script with arguments
        print(uptime, breaktime)
        subprocess.Popen(["takeabreak_run", uptime, breaktime])
    
    def kill(pid):
        # function to stop the script
        subprocess.Popen(["kill", pid])
    
    def message(msg):
        # function to send a notification
        subprocess.Popen(["notify-send", msg])
    
    if arg == "toggle":
        # the section below handles toggling the script
        pid = check_running()
        if pid != False:
            kill(pid)
            message("Take a break stopped...")
        else:
            try:
                # if settings file exist: message, displaying set time
                time_set = open(setting).read().strip().split()
                uptime = time_set[0]; breaktime = time_set[1]
            except FileNotFoundError:
                # if no settings were made: use defaults
                uptime = default_up; breaktime = default_break
            message("Take a break started ("+uptime+"/"+breaktime+")")
            start(uptime, breaktime)
    
    if arg == "timeset":
        # the section below handle creating the settings file and/or setting the time
        command = 'zenity --entry --title="Edit time settings" --text="Enter uptime & breaktime:" --entry-text "'+\
                  default_up+' '+default_break+'"'
        try:
            t_set = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8").split()
            try:
                if len([int(n) for n in t_set]) != 2:
                    msg = 'zenity --warning --text="Please enter both (and only) up- and breaktime."'
                else:
                    msg = 'zenity --info --title="New setings" --text="Timesettings succsfully changed."'
                    open(setting, "wt").write((" ").join(t_set))
                    pid = check_running()
                    # if script runs, restart with new values
                    if pid != False:
                        kill(pid)
                        start(t_set[0], t_set[1])
                        message("Take a break restarted "+("/").join(t_set))
            except ValueError:
                msg = 'zenity --warning --text="Please only enter integers."'
            subprocess.Popen(["/bin/bash", "-c", msg])
        except subprocess.CalledProcessError:
            pass
    

编辑时间设置

基本的”GUI”应该没有太多解释。要编辑时间设置,请将启动器添加到Unity Launcher(将.desktop文件拖到Unity Launcher上或将“休息”锁定到启动器),right-click启动器并选择“更改时间设置”:

software-recommendation,lock-screen,ubuntu

随后输入”uptime”(分钟)和”breaktime”(分钟),用空格分隔。脚本有内置注意事项错误输入:)

如果在脚本运行时更改了时间设置,则会使用更改的设置自动重新启动:

software-recommendation,lock-screen,ubuntu



FINALLY

现在可能是最后一次编辑:项目现在在launchpad上 – 有很多变化,更多选项等等。

sudo add-apt-repository ppa:vlijm/takeabreak
sudo apt-get update
sudo apt-get install takeabreak

随意提交错误等here,或发表评论here。感谢orschiro提出的好问题,以及Rinzwind的鼓励!

剩余休息时间(使用倒计时选项)

software-recommendation,lock-screen,ubuntu

software-recommendation,lock-screen,ubuntu

software-recommendation,lock-screen,ubuntu

次佳解决思路

您可能还想考虑Workrave,尽管它已不再开发中。我发现它易于使用且高度可定制。它还有一些很好的统计数据,关于你如何使用计算机以及你采取了多少休息。最后,我相信它也可以在许多计算机之间同步,例如,如果你在笔记本电脑和学校计算机上工作,这很有用。

software-recommendation,lock-screen,ubuntu

编辑:它有许多我没有提到的其他功能,比如在屏幕被阻止时建议你做一些练习。它只能考虑你使用电脑的时间,所以当你从厕所回来时它不会提示你休息:)

编辑2:

请务必查看”Reading”模式!

如果您没有做太多事情(没有鼠标,没有键盘事件),上面只计算您积极使用计算机的时间的功能可以被视为一个错误,因为它只会在您累计使用1小时时提示您休息(或者你设置了多少时间)。在这些情况下,启用”Reading”模式将使其在准确的时间提示,无论使用情况如何。

第三种解决思路

原油,极简主义,命令行方式:

sleep 1500; gnome-screensaver-command -l; sleep 300; killall gnome-screensaver

这也可以转换为桌面快捷方式或在.bashrc中转换为功能

为什么1500和300?因为这是秒,每分钟1500秒/60秒= 25分钟。


下面是一个允许设置变量会话和中断时间的计时器脚本,以及发出中断信号的方法。

请记住,linux上的任何脚本都必须保存为文件,并具有使用chmod +x /path/to/script.sh设置的可执行权限。完成后,您可以将脚本绑定到How do I bind .sh files to keyboard combination?中显示的快捷方式,或创建一个桌面快捷方式,如How can I create launchers on my desktop?中所示

启动脚本时,您应该看到如下菜单:

software-recommendation,lock-screen,ubuntu

#!/bin/bash

# Author: Serg Kolo
# Date : Nov 17th, 2015
# Purpose: pomodoro timer script,
# with bunch of options
# Written for: https://askubuntu.com/q/696620/295286

#####################################################
# screenSaver function
# this one uses gnome-screensaver-command for locking
# and killall for unlocking the screen;
# $1 is provided from chooseBreakMethod function
#####################################################

function screenSaver
{
  gnome-screensaver-command -l; sleep $1 ; killall gnome-screensaver 
}


##############################################
# dialogBreak function
# this serves as "screensaver". The screen is never 
# actually locked but rather we open terminal window 
# with a simple command line dialog
# in full sccrean mode
# $1 provided in chooseBreakMethod function
##################################################
function dialogBreak
{
 gnome-terminal --full-screen  -e  "bash -c 'sleep $1 | dialog --progressbox \"TAKE A BREAK\" 100 100 ' "
}

#################################################################
# dimScreen function 
# dims the screen using xrandr; the --brightness 
# can be configured
# for full or partial dimming using decimal values
# from 1 to 0
# $1 is provided from chooseBreakMethod function
################################################################

function dimScreen
{
  xrandr  | awk '$2 == "connected" {print $1}' | xargs -I % xrandr --output % --brightness 0.5
  notify-send 'Take a Break'
  sleep $1
  xrandr  | awk '$2 == "connected" {print $1}' | xargs -I % xrandr --output % --brightness 1
}

##############################
# getSettings function
# This is where the user enters 
# the settings they want
# All the values must be integers
#############################
function getSettings
{
  FORM=$(zenity --forms \ --title="Sergiy's Tomato Script" --text="Choose this session options" \
   --add-entry="Number of Sessions (how many loops)" \
   --add-entry="Session time (minutes)" \
   --add-entry="Break time (minutes)" \
   --add-entry="Dim,dialog,or screensaver? (1,2,3)" \
   --separator=" " )  

  [ $? -eq 0 ] || exit 1

   echo $FORM
}

################################
# chooseBreakMethod function
# A helper function that calls appropriate
# break method, based on the value we got
# from getSettings function
# Because dialogBreak calls gnome-terminal
# this function exits, so it doesn't wait
# Therefore we need to add additional sleep
# command
###############################

function chooseBreakMethod
{

 # $1 is method passed from  ${SETS[3]}
 # $2 is break time passed from ${SETS[2]}
  case $1 in
    1) dimScreen $2 ;;
        2) dialogBreak $2 ; sleep $2 ;;
    3) screenSaver $2 ;;
  esac

}


function minutesToSeconds
{
  echo $(($1*60))
}

#################
# MAIN
#################

# get user settings and store them into array
# Item 0 : num sessions
# Item 1 : session duration
# Item 2 : break duration
# Item 3 : break method - lockscreen, dialog, or just
# turn off the screen 
# SETS == settings
SETS=( $(getSettings) )

COUNTER=${SETS[0]}

#######################################
# This is where most of the job is done
# we loop according to number of session
# specified in the  getSettings function
#########################################

notify-send 'Session started'
while [ $COUNTER -ne 0  ]; do

  sleep $( minutesToSeconds ${SETS[1]} ) # session timer
  chooseBreakMethod ${SETS[3]} $( minutesToSeconds ${SETS[2]} )
  COUNTER=$(($COUNTER-1))
done

notify-send "tomatoScript is done"
####### END OF SCRIT ###########

第四种思路

这是另一个名为Safe Eyes的工具,用于同一目的。

sudo add-apt-repository ppa:slgobinath/safeeyes
sudo apt-get update
sudo apt-get install safeeyes

software-recommendation,lock-screen,ubuntu

特征:

  • 眼保健操短暂休息

  • 长时间休息以改变身体姿势和热身

  • 对那些沉迷于电脑的人严格休息

  • 使用全屏应用程序时请勿打扰(例如:看电影)

  • 在休息期间禁用键盘

  • 每次休息前通知

  • 支持多个显示

  • 如果系统空闲,则自动暂停

  • 休息结束时可选的声音警报

  • Multi-language支持

有关详细信息:https://github.com/slgobinath/SafeEyes

第五种思路

为此,我使用了xwrits多年。

sudo apt-get install xwrits

默认情况下,每55分钟休息5分钟,但根据man page,这些时间可分别通过breaktimetypetime命令行选项进行自定义。您还可以使用+lock选项控制是否锁定屏幕。所以要将它设置为每25分钟一次5分钟的休息时间锁定你,你应该像这样运行它

xwrits typetime=25 breaktime=5 +lock &

参考资料

本文由Ubuntu问答整理, 博文地址: https://ubuntuqa.com/article/1188.html,未经允许,请勿转载。