在家和办公室写了一些笔记,有时候在书写过程中因为各种原因思路中断,等回到家有一些思路的时候发现办公室的笔记忘记提交到 Github
仓库,所以写了一个定时任务,每天在下班时间定时提交。
google一番,发现自带定时任务工具launchd
。MacOS通过 launchctl
命令加载plist
配置文件来管理定时任务。
plist存放目录
/Library/LaunchDaemons -> 只要系统启动了,哪怕用户不登陆系统也会被执行
/Library/LaunchAgents -> 当用户登陆系统后才会被执行
~/Library/LaunchAgents 由用户自己定义的任务项
/System/Library/LaunchAgents 由Mac OS X为用户定义的任务项
/System/Library/LaunchDaemons 由Mac OS X定义的守护进程任务项
plist标签说明
1
2
3
4
5
6
| 1. Label:对应的需要保证全局唯一性;
2. Program:要运行的程序;
3. ProgramArguments:命令语句
4. StartCalendarInterval:运行的时间,单个时间点使用dict,多个时间点使用 array <dict>
5. StartInterval:时间间隔,与StartCalendarInterval使用其一,单位为秒
6. StandardInPath、StandardOutPath、StandardErrorPath:标准的输入输出错误文件,这里建议不要使用 .log 作为后缀,会打不开里面的信息。
|
launchctl命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| # 加载任务, -w选项会将plist文件中无效的key覆盖掉,建议加上
$ launchctl load -w com.xx.xx.plist
# 删除任务
$ launchctl unload -w com.xx.xx.plist
# 查看任务列表, 使用 grep '任务部分名字' 过滤
$ launchctl list | grep 'com.xx.xx'
# 开始任务
$ launchctl start com.xx.xx.plist
# 结束任务
$ launchctl stop com.xx.xx.plist
|
编写脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| #!/bin/bash
###
# @FilePath: /scripts/commit.sh
# @Author: kbsonlong [email protected]
# @Date: 2024-05-13 11:15:23
# @LastEditors: kbsonlong [email protected]
# @LastEditTime: 2024-05-13 12:31:45
# @Description:
# Copyright (c) 2024 by kbsonlong, All Rights Reserved.
###
datetime="$(date +%Y-%m-%d_%H:%M:%S)"
workdir=$(cd $(dirname $0); pwd)
cd "${workdir}" || exit
if [[ "${1}" == "pull" ]]; then
git pull --quiet
elif [[ "${1}" == "push" ]]; then
git add .
git commit -m "Auto commit by ${datetime}"
git push
else
echo "Usage: $0 [pull|push]"
fi
|
编写Plist
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<!-- 唯一标识符 -->
<string>com.kbsonlong.launchctl.blog.git</string>
<!-- 启动程序 -->
<key>Program</key>
<string>/Users/zengshenglong/Code/HandBooks/alongparty.cn/scripts/commit.sh</string>
<!-- 启动参数 -->
<key>ProgramArguments</key>
<array>
<!-- 第一个为启动程序 -->
<string>/Users/zengshenglong/Code/HandBooks/alongparty.cn/scripts/commit.sh</string>
<!-- <string>pull</string> -->
</array>
<!-- 加载时候是否启动 -->
<key>RunAtLoad</key>
<true/>
<!-- 定时器 -->
<key>StartCalendarInterval</key>
<array>
<dict>
<key>Hour</key>
<integer>9</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
<dict>
<key>Hour</key>
<integer>19</integer>
<key>Minute</key>
<integer>0</integer>
</dict>
</array>
<!-- 日志输出 -->
<key>StandardOutPath</key>
<string>/Users/zengshenglong/Code/HandBooks/alongparty.cn/log/run.log</string>
<key>StandardErrorPath</key>
<string>/Users/zengshenglong/Code/HandBooks/alongparty.cn/log/run.err</string>
</dict>
</plist>
|