コンテンツにスキップ

GitHub Actionsで定期実行を5分で設定する方法

この記事の対象者

  • GitHub Actionsで定期的なタスクを自動化したい開発者

この記事のポイント

  1. GitHub Actionsのscheduleトリガーが設定できる
  2. cron式の基本的な書き方が理解できる
  3. Claude Codeを定期実行できる

定期実行の仕組み

GitHub Actionsのscheduleイベントは、指定した時刻にワークフローを自動実行します。 内部的にはcron式を使用しますが、GitHub上で完結するため、サーバー設定は不要です。

実装手順

ステップ1: ワークフローファイルを作成

.github/workflows/scheduled-task.ymlを作成:

name: 定期実行タスク
on:
  schedule:
    - cron: '0 9 * * *'  # 毎日9時(UTC)
  workflow_dispatch:  # 手動実行も可能に

ステップ2: Claude Code実行ジョブを追加

jobs:
  run-claude:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Claude Code実行
        env:
          CLAUDE_API_KEY: ${{ secrets.CLAUDE_API_KEY }}
        run: |
          # Claude Codeで自動化タスクを実行
          npx claude-code --task "デイリーレポート生成"

ステップ3: GitHubにプッシュして有効化

git add .github/workflows/scheduled-task.yml
git commit -m "Add scheduled workflow"
git push origin main

よく使うcron式パターン

実行タイミングcron式日本時間(JST)
毎日朝9時0 0 * * *9:00
平日朝9時0 0 * * 1-59:00(月-金)
毎週月曜9時0 0 * * 1月曜9:00
毎月1日9時0 0 1 * *1日9:00
6時間ごと0 */6 * * *0,6,12,18時

※GitHub ActionsはUTC基準。日本時間は+9時間

トラブルシューティング

症状原因解決策
実行されないcron式の誤りcrontab.guruで検証
時刻がずれるタイムゾーンUTC基準で計算(JST-9時間)
60日で停止非アクティブリポジトリに定期的にコミット
高度な設定(クリックで展開) ### 複数スケジュールの設定
on:
  schedule:
    - cron: '0 0 * * *'  # 毎日
    - cron: '0 12 * * 5'  # 金曜昼
### 環境別の実行
jobs:
  scheduled-task:
    strategy:
      matrix:
        environment: [dev, staging, prod]
    runs-on: ubuntu-latest
    steps:
      - name: Run for ${{ matrix.environment }}
        run: echo "Running for ${{ matrix.environment }}"
### エラー通知の追加
- name: エラー通知
  if: failure()
  uses: actions/github-script@v7
  with:
    script: |
      github.rest.issues.create({
        owner: context.repo.owner,
        repo: context.repo.repo,
        title: 'Scheduled task failed',
        body: 'Check the workflow run for details'
      })

次のステップ


この記事は、従来の複数のcron関連記事から GitHub Actions に特化した内容を抽出・整理したものです。