立即注册  找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 25|回复: 0

使用systemd定时器定时访问URL并等待30秒

[复制链接]

使用systemd定时器定时访问URL并等待30秒

[复制链接]

187

主题

103

回帖

1203

积分

管理员

积分
1203
admin

187

主题

103

回帖

1203

积分

管理员

积分
1203
2025-6-8 08:07:41 | 显示全部楼层 |阅读模式
# 使用systemd定时器定时访问URL并等待30秒

要在CentOS 7上使用systemd定时器每天定时访问不同URL,并在访问时等待30秒,可以按照以下配置:

## 配置方案

### 1. 创建服务单元文件

#### 第一个URL服务(4:02访问,等待30秒)
sudo vim /etc/systemd/system/url-access-early.service`:
```ini
[Unit]
Description=Early Morning URL Access Service with 30s wait

[Service]
Type=oneshot
ExecStart=/bin/sh -c 'curl -s --max-time 30 http://first.example.com/api/ping && sleep 30'
```

#### 第二个URL服务(4:20访问,等待30秒)
sudo vim/etc/systemd/system/url-access-late.service`:
```ini
[Unit]
Description=Late Morning URL Access Service with 30s wait

[Service]
Type=oneshot
ExecStart=/bin/sh -c 'curl -s --max-time 30 http://second.example.com/api/ping && sleep 30'
```

### 2. 创建定时器单元文件

#### 第一个定时器(4:02)
sudo vim /etc/systemd/system/url-access-early.timer`:
```ini
[Unit]
Description=Run early URL access daily at 4:02 AM with 30s wait

[Timer]
OnCalendar=*-*-* 04:02:00
Persistent=true
Unit=url-access-early.service

[Install]
WantedBy=timers.target
```

#### 第二个定时器(4:20)
sudo vim /etc/systemd/system/url-access-late.timer`:
```ini
[Unit]
Description=Run late URL access daily at 4:20 AM with 30s wait

[Timer]
OnCalendar=*-*-* 04:20:00
Persistent=true
Unit=url-access-late.service

[Install]
WantedBy=timers.target
```

### 3. 启用并启动定时器

```bash
# 重新加载systemd配置
sudo systemctl daemon-reload

# 启用并启动定时器
sudo systemctl enable --now url-access-early.timer
sudo systemctl enable --now url-access-late.timer
```

### 4. 验证配置

```bash
# 查看定时器状态
systemctl list-timers --all

# 检查下次执行时间
systemctl status url-access-early.timer
systemctl status url-access-late.timer
```

## 高级配置选项

1. **添加超时控制**:
   ```ini
   ExecStart=/bin/sh -c 'timeout 60 curl -s --max-time 30 http://example.com/api/ping && sleep 30'
   ```

2. **记录完整日志**:
   ```ini
   ExecStart=/bin/sh -c 'date >> /var/log/url-access.log; curl -v --max-time 30 http://example.com/api/ping >> /var/log/url-access.log 2>&1 && sleep 30'
   ```

3. **添加重试机制**:
   ```ini
   ExecStart=/bin/sh -c 'for i in 1 2 3; do curl -s --max-time 30 http://example.com/api/ping && break || sleep 10; done && sleep 30'
   ```

这样配置后,系统会在每天指定时间访问URL,并在访问完成后等待30秒。如果需要在访问前等待30秒,可以将sleep命令放在curl之前。

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|小黑屋|学无止境

GMT+8, 2026-9-12 11:21 , Processed in 0.264996 second(s), 19 queries .

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表