GitHub Actions脚本 运行 node 定时脚本

21 min read
name: Hourly Job

on:
  push:
    branches: [main]
  schedule:
    - cron: "0 * * * *" # 每小时执行

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3

      - name: Cache node_modules
        uses: actions/cache@v2
        with:
          path: node_modules
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: "16.x"

      - name: Install Dependencies
        run: npm install

      - name: Run Hourly Job
        if: ${{ github.event_name == 'push' || github.event_name == 'schedule' }}
        run: |
          node index.js 
          echo ${{ secrets.GITHUB_TOKEN }}
          echo ${{ github.actor }}
          echo 123
          git config --local user.email "[email protected]"
          git config --local user.name "bot"
          git remote set-url origin https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}
          git add .
          git commit -m "update by github action"
          git push

Cache node_modules 步骤中,使用 actions/cache@v2 action 缓存 node_modules 文件夹。缓存的 key 是根据 package-lock.json 的 hash 值计算得出的,以确保缓存的正确性。同时,restore-keys 字段中指定了恢复缓存所需要的 key,以避免使用不同的操作系统和 Node.js 版本时无法恢复缓存。

使用 actions/checkout@v3 检出代码时,可以指定 fetch-depth: 0 来完整地检出所有的 Git 历史记录,这对于某些操作(如生成代码覆盖率报告)非常有用。

哈希值是可选的,可以在键后添加哈希值,以在不同的缓存版本之间进行区分。

github actions 的仓库权限

新的管理员设置允许您在组织或存储库中设置令牌的默认权限。

You can choose between two options:
您可以在两个选项之间进行选择:

  • Read/write for all scopes (current default)
    所有作用域的读/写(当前默认值)
  • Read repo contents 读取存储库内容

解决 "github actions" remote: Write access to repository not granted.

使用 GITHUB_TOKEN 变量

At the start of each workflow run, GitHub automatically creates a unique GITHUB_TOKEN secret to use in your workflow. You can use the GITHUB_TOKEN to authenticate in a workflow run.
在每个工作流运行开始时,GitHub会自动创建一个唯一的 GITHUB_TOKEN 密码用于您的工作流。您可以使用 GITHUB_TOKEN 在工作流运行中进行身份验证。

在每个作业开始之前,GitHub会为作业获取一个安装访问令牌。 GITHUB_TOKEN 在作业完成时或最多24小时后过期