在Ubuntu系统中,设置定时器以发送短信通知可以通过多种方式实现。以下是几种常见的方法:
pip install twilio
from twilio.rest import Client
# 你的Twilio账户SID和Auth Token
account_sid = 'your_account_sid'
auth_token = 'your_auth_token'
# 创建Twilio客户端
client = Client(account_sid, auth_token)
# 发送短信
message = client.messages.create(
body="Hello from Python!",
from_='your_twilio_number', # 你的Twilio号码
to='recipient_phone_number' # 收件人号码
)
print(f"Message sent with SID: {message.sid}")
请将your_account_sid
、your_auth_token
、your_twilio_number
和recipient_phone_number
替换为实际的值。sudo apt-get install gammu
gammu sendsms TEXT -text "message" "phone_number"
请将message
替换为短信内容,phone_number
替换为收件人号码。crontab -e
0 6 * * * /path/to/your_script.sh
请将/path/to/your_script.sh
替换为实际脚本路径。创建服务单元文件:创建一个名为mytimer.service
的文件:
sudo nano /etc/systemd/system/mytimer.service
添加以下内容:
[Unit]
Description=My Custom Timer Service
[Service]
ExecStart=/path/to/your/script.sh
请将/path/to/your/script.sh
替换为实际脚本路径。
创建定时器单元文件:创建一个名为mytimer.timer
的文件:
sudo nano /etc/systemd/system/mytimer.timer
添加以下内容:
[Unit]
Description=Run My Custom Timer Service every day at 8 AM
[Timer]
OnCalendar=*-*-* 08:00:00
Persistent=true
[Install]
WantedBy=timers.target
请根据需要调整触发时间。
重新加载systemd配置:
sudo systemctl daemon-reload
启用并启动定时器:
sudo systemctl enable --now mytimer.timer
查看定时器状态:
sudo systemctl status mytimer.timer
通过以上方法,你可以在Ubuntu系统中设置定时器以发送短信通知。选择适合你需求的方法进行配置即可。