GitHub Actions 定时任务:自动化备份、清理与报表

GitHub Actions 定时任务实战:cron 语法与调度策略、自动化备份(数据库/仓库/Artifact)、过期数据清理(Artifact/日志/缓存)、依赖更新报表生成、健康检查与站点监控(HTTP ping/证书过期检查)、周期性测试(端到端/性能回归)、Stale Issue/PR 自动清理、报告邮件/Slack 推送、成本优化(运行时间/并行度)

除了 CI/CD,GitHub Actions 的 schedule 触发器让它成为强大的定时任务平台。从每日数据库备份到每周依赖报表,从证书过期检查到 Stale Issue 清理——cron 驱动的自动化工作流可以接管大量运维琐事。本文覆盖 cron 语法、备份策略、清理任务、健康监控和成本优化——让 GitHub Actions 成为你的运维机器人。


一、cron 语法与调度策略

1.1 GitHub Actions cron

on:
  schedule:
    # 分 时 日 月 星期
    - cron: '0 9 * * 1'   # 每周一 9:00 UTC
    - cron: '0 0 * * *'   # 每天 0:00 UTC
    - cron: '0 */6 * * *' # 每 6 小时
    - cron: '0 2 1 * *'   # 每月 1 日 2:00 UTC

1.2 时区转换

UTC 转北京时间(UTC+8):
cron: '0 1 * * *'  # UTC 1:00 = 北京时间 9:00
cron: '0 9 * * *'  # UTC 9:00 = 北京时间 17:00

# GitHub Actions 只支持 UTC,需手动换算

1.3 调度可靠性

- schedule 事件不保证精确时间,可能延迟 5-15 分钟
- 仓库 60 天无活动会暂停 schedule
- 建议:重要的定时任务加一个手动触发(workflow_dispatch)

二、自动化备份

2.1 仓库备份

name: Backup Repository

on:
  schedule:
    - cron: '0 2 * * *'  # 每天 2:00 UTC
  workflow_dispatch:

jobs:
  backup:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # 完整历史

      - name: Create bundle
        run: git bundle create repo-backup.bundle --all

      - name: Upload to S3
        uses: jakejarvis/s3-sync-action@v0.5.1
        with:
          args: --acl private
        env:
          AWS_S3_BUCKET: my-backups
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          SOURCE_DIR: repo-backup.bundle
          DEST_DIR: github-backups/${{ github.repository }}/${{ github.run_id }}/

2.2 Artifact 备份

      - name: Download all artifacts
        uses: actions/download-artifact@v3
        with:
          path: artifacts

      - name: Backup to cloud storage
        run: |
          tar czf artifacts-${{ github.run_id }}.tar.gz artifacts/
          aws s3 cp artifacts-${{ github.run_id }}.tar.gz s3://backups/

三、过期数据清理

3.1 Artifact 自动清理

name: Cleanup Old Artifacts

on:
  schedule:
    - cron: '0 3 * * 0'  # 每周日 3:00 UTC

jobs:
  cleanup:
    runs-on: ubuntu-latest
    steps:
      - name: Delete old artifacts
        uses: geekyeggo/delete-artifact@v2
        with:
          name: |
            build-*
            test-results-*
          failOnError: false

3.2 Action 缓存清理

      - name: Clear old caches
        uses: actions/gh-actions-cache@v1
        with:
          operation: delete
          key: v1-deps-
      - name: Clear old workflow runs
        uses: Mattraks/delete-workflow-runs@v2
        with:
          retain_days: 30
          keep_minimum_runs: 10

3.3 日志保留策略

# 仓库级设置:
# Settings → Actions → General → Artifact and log retention
# 默认 90 天,可设为 30 天节省存储

四、健康检查与监控

4.1 HTTP 端点监控

name: Health Check

on:
  schedule:
    - cron: '*/5 * * * *'  # 每 5 分钟

jobs:
  ping:
    runs-on: ubuntu-latest
    steps:
      - name: Check API health
        run: |
          response=$(curl -s -o /dev/null -w "%{http_code}" https://api.example.com/health)
          if [ "$response" != "200" ]; then
            echo "API is down! Status: $response"
            exit 1
          fi

      - name: Notify on failure
        if: failure()
        uses: slackapi/slack-github-action@v1
        with:
          payload: |
            {"text": "🚨 API health check failed!"}

4.2 SSL 证书过期检查

      - name: Check SSL certificate expiry
        run: |
          expiry=$(echo | openssl s_client -servername api.example.com -connect api.example.com:443 2>/dev/null | openssl x509 -noout -dates | grep notAfter | cut -d= -f2)
          expiry_epoch=$(date -d "$expiry" +%s)
          now_epoch=$(date +%s)
          days_until_expiry=$(( (expiry_epoch - now_epoch) / 86400 ))
          
          echo "Certificate expires in $days_until_expiry days"
          if [ "$days_until_expiry" -lt 30 ]; then
            echo "WARNING: Certificate expires in less than 30 days!"
            exit 1
          fi

4.3 依赖漏洞日报

      - name: Security audit
        run: npm audit --audit-level=high

      - name: Generate report
        if: failure()
        run: |
          npm audit --json > audit-report.json
          # 发送到 Slack/邮件

五、Stale Issue/PR 清理

5.1 配置

name: Stale Manager

on:
  schedule:
    - cron: '0 8 * * *'

jobs:
  stale:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/stale@v8
        with:
          stale-issue-message: 'This issue has been inactive for 30 days. Will close in 7 days if no update.'
          stale-pr-message: 'This PR has been inactive for 30 days. Will close in 7 days if no update.'
          days-before-stale: 30
          days-before-close: 7
          stale-issue-label: 'stale'
          exempt-issue-labels: 'pinned,security'
          exempt-pr-labels: ' wip'

六、报表生成与通知

6.1 每周构建报表

      - name: Generate weekly report
        run: |
          echo "## Weekly CI Report" > report.md
          echo "- Total runs: ${{ github.run_number }}" >> report.md
          echo "- Success rate: $(cat success-rate.txt)" >> report.md

      - name: Send email
        uses: dawidd6/action-send-mail@v3
        with:
          server_address: smtp.gmail.com
          server_port: 587
          username: ${{ secrets.EMAIL_USER }}
          password: ${{ secrets.EMAIL_PASS }}
          subject: Weekly CI Report
          to: team@example.com
          from: ci@example.com
          html_body: file://report.md

七、成本优化

7.1 运行时间优化

- 使用缓存(actions/cache)减少依赖安装时间
- 并行化独立的 job(needs 依赖管理)
- 使用 ubuntu-latest(最便宜的 runner)
- 定时任务用小型 runner(如有 self-hosted)

7.2 存储优化

- 限制 Artifact 保留时间(30 天)
- 定期清理旧 workflow runs
- 大文件不上传 Artifact(用外部存储)

7.3 计费须知

# GitHub Actions 免费额度:
# - 公共仓库:无限制
# - 私有仓库:2000 分钟/月(Linux)
# - 超出:$0.008/分钟(Linux)

# Self-hosted runner:免费但需维护

总结

GitHub Actions 的 schedule 触发器让它不只是 CI 工具,而是一个完整的自动化平台。cron 工作流适合:定时备份(仓库/数据库/Artifact)、健康检查(HTTP ping/证书过期)、数据清理(过期 Artifact/缓存/日志)、报告生成(安全审计/构建统计)、Issue/PR 治理(Stale 标记)。关键注意事项:GitHub Actions cron 只支持 UTC、仓库 60 天无活动会暂停 schedule、重要任务加 workflow_dispatch 手动触发。配合 Slack/邮件通知,可以实现「无人值守」的运维自动化。

延伸阅读:

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「github-actions」更多文章

  1. GitHub Actions Go/Rust CI:交叉编译、静态检查与发布
  2. GitHub Actions Java/JVM CI:Maven、Gradle、JaCoCo 与 Jib 容器化
  3. GitHub Actions PR 自动化:标签、审查、合并与发布