Scheduling a Job in Jenkins – 在Jenkins中调度一个工作

最后修改: 2018年 1月 7日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this article, we’ll cover various ways of scheduling jobs in Jenkins.

在这篇文章中,我们将介绍Jenkins中调度作业的各种方法。

We’ll begin with scheduling a simple job that performs something as simple as printing a plain text message. And we’ll evolve the example into scheduling a job that gets automatically triggered by changes in an SCM repository such as GitHub, Bitbucket, etc.

我们将从调度一个简单的作业开始,这个作业执行的是打印纯文本信息这样简单的事情。我们将把这个例子发展为调度一个由SCM仓库(如GitHub、Bitbucket等)中的变化自动触发的工作。

2. Initial Setup

2.初始设置

We assume that JDK and Maven have been installed in Global Tool Configuration with names as JDK9.0.1 and Maven3.5.2, respectively, on the Jenkins server.

我们假设JDK和Maven已经在Global Tool Configuration中安装,名称分别为JDK9.0.1和Maven3.5.2,在Jenkins服务器上。

It also assumes that we’ve got access to an SCM repository such as Bitbucket with a Maven project properly set up.

它还假设我们已经访问了SCM仓库,如Bitbucket,并正确设置了Maven项目。

3. Scheduling a Simple Job

3.安排一个简单的工作

In the job configuration page, let’s scroll down straight to the Build Triggers section. Since we intend to create a straightforward job, let’s select the checkbox marked Build periodically. As soon as we select this checkbox, a Text Box is displayed with the Schedule label.

在作业配置页面,让我们直接向下滚动到Build Triggers部分。由于我们打算创建一个简单的作业,让我们选择标有Build periodically的复选框。一旦我们选择了这个复选框,一个文本框就会显示Schedule标签。

We have to provide value in a Cron-compliant format. There’s extensive information available on the page if we click the question mark next to the box.

我们必须以Cron兼容的格式提供价值。如果我们点击方框旁边的问号,页面上有大量的信息。

Let’s type */2 * * * * here, which represents an interval of two minutes:

让我们在这里输入*/2 * * *,这代表两分钟的间隔。

 

Upon tabbing out of the text box, we can see information right beneath the box. It tells us about when will the job run next.

在退出文本框时,我们可以看到文本框下面的信息。它告诉我们该工作下一步将在什么时候运行。

Let’s save the job – in about two minutes, we should see the status of the first execution of the job:

让我们保存作业–大约两分钟后,我们应该看到作业的第一次执行状态。

Since we’ve configured the job to run every two minutes, we should see multiple build numbers when we go back to the job dashboard after waiting for some time.

由于我们将作业配置为每两分钟运行一次,所以当我们在等待一段时间后回到作业仪表板时,我们应该看到多个构建编号。

4. Creating a Job That Polls SCM

4.创建一个调查SCM的工作

Let’s move one step forward and create a job that pulls source code from SCM repository such as Bitbucket and performs a build.

让我们再往前走一步,创建一个作业,从SCM库(如Bitbucket)中提取源代码并执行构建。

Let’s create a new job as explained in the previous section, with a few modifications.

让我们按照上一节的解释创建一个新的工作,并做一些修改。

In the Build Triggers section, instead of selecting Build Periodically, let’s select Poll SCM. As soon as we do that, we should see a text box with Label Schedule.

Build Triggers部分,不要选择Build Periodically,让我们选择Poll SCM。一旦我们这样做,我们应该看到一个标签为Schedule的文本框。

Let’s type */5 * * * * in this box, which means we want to schedule the job to run every 5 minutes:

让我们在此框中输入*/5 * * *,这意味着我们要安排该作业每5分钟运行一次。

Let’s scroll up to Source Code Management section. Upon selecting the radio button next to Git, a new section appears labeled as Repositories.

让我们向上滚动到源代码管理部分。选择Git旁边的单选按钮后,会出现一个新的部分,标注为Repositories

This is where we need to configure details of our SCM repository. Let’s type the URL of the SCM repository in the Repository URL text field:

这里我们需要配置我们的SCM资源库的细节。让我们在Repository URL文本字段中输入SCM资源库的URL。

We also need to provide user credentials so that Jenkins can access the repository.

我们还需要提供用户凭证,以便Jenkins能够访问版本库。

Let’s click the Add button next to Credentials, which will display a pop-up screen to create the user credentials.

让我们点击Credentials旁边的Add按钮,这将显示一个弹出屏幕来创建用户凭证。

Let’s select the Kind as Username with Password. We’ll have to type the username and password in the designated text fields:

让我们选择KindUsername with Password。我们将不得不在指定的文本字段中输入用户名和密码。

On click of Add button, we’re taken back to the Source Code Management section.

点击添加按钮,我们会被带回源代码管理部分。

Let’s select this user credential in the drop-down next to Credentials:

让我们在Credentials旁边的下拉菜单中选择这个用户凭证。

Now, the last thing we need to do is to set up the build script.

现在,我们需要做的最后一件事是设置构建脚本。

Let’s scroll down to Build section, click Add build step and select Execute Shell. Since we’re working on a Maven project in the SCM repository, we need to type mvn clean install, which will perform a Maven build.

让我们向下滚动到Build部分,点击Add build step,选择Execute Shell。由于我们正在SCM仓库中处理一个Maven项目,我们需要输入mvn clean install,这将执行Maven构建。

Let’s try to understand what we’ve done here.

让我们试着理解我们在这里做了什么。

We’ve created a job that is scheduled to run every 5 minutes. The job’s been configured to pull source code from the master branch of the given Bitbucket repository.

我们已经创建了一个工作,计划每5分钟运行一次。该作业被配置为从给定的Bitbucket仓库的主分支拉取源代码

It will use provided user credentials to log in to Bitbucket.

它将使用提供的用户凭证来登录Bitbucket。

After pulling the source code, the job will execute the script containing a provided Maven command.

拉取源代码后,该作业将执行包含所提供的Maven命令的脚本。

Now, if we save and wait approximately five minutes, we should see the build execution in Build History section on the job dashboard.

现在,如果我们保存并等待大约五分钟,我们应该在作业仪表板的Build History部分看到构建的执行。

The Console Output should show the output of the Maven build. We can see in the console output that the source code has been pulled from Bitbucket and the command mvn clean install has been executed:

控制台输出应显示Maven构建的输出。我们可以在控制台输出中看到,源代码已经从Bitbucket拉出,mvn clean install命令已经被执行。

Since it’s a Maven build, the console output might be very long depending on the number of Maven dependencies that are downloaded.

由于是Maven构建,控制台输出可能很长,这取决于下载的Maven依赖项的数量

But at the end of the output, we should see BUILD SUCCESS message.

但是在输出的最后,我们应该看到BUILD SUCCESS消息。

5. Creating a Job That Uses Pipeline as Script

5.创建一个使用管道作为脚本的作业

So far, we’ve seen how to create jobs that execute at the predefined scheduled time.

到目前为止,我们已经看到如何创建在预定时间执行的作业。

Now, let’s create a job that’s not bound to any particular schedule. Instead, we’ll configure it to automatically trigger whenever there is a new commit in SCM repository.

现在,让我们创建一个不受任何特定时间表约束的作业。相反,我们将配置它在SCM仓库有新提交时自动触发。

Going back to Jenkins dashboard, let’s click New Item. This time, instead of Freestyle project, we’ll select Pipeline. Let’s name this job PipelineAsScriptJob.

回到Jenkins仪表板,让我们点击New Item。这一次,我们不选择Freestyle项目,而选择Pipeline。让我们把这个工作命名为PipelineAsScriptJob.

Upon clicking OK button, we’ll be taken to the pipeline configuration page. This page has several sections such as “General”, “Build Triggers”, “Advanced Project Options”, and “Pipeline”.

点击 “确定 “按钮后,我们将被带到管道配置页面。这个页面有几个部分,如”一般”,”构建触发器”,”高级项目选项”,和”管道”

Let’s scroll down to “Build Triggers” section and the select checkbox next to Build when a change is pushed to Bitbucket. This option will be available only if we’ve installed the Bitbucket Plugin:

让我们向下滚动到”Build Triggers”部分,选择Build when a change is pushed to Bitbucket旁边的复选框。这个选项只有在我们安装了Bitbucket插件的情况下才可用

Let’s scroll down to Pipeline section. We need to select Pipeline Script in the drop-down next to Definition.

让我们向下滚动到管道部分。我们需要在Definition旁边的下拉菜单中选择Pipeline Script

The Text Box just below this drop-down is waiting for the script to be placed in. There’re two ways of doing this.

就在这个下拉框下面的文本框正在等待脚本的放置。有两种方法可以做到这一点。

We can either type the whole script, or we can make use of a utility provided by Jenkins, which is known as Pipeline Syntax.

我们可以键入整个脚本,或者我们可以利用Jenkins提供的一个工具,这被称为Pipeline Syntax

Let’s choose the second option:

让我们选择第二个选项。

On click of Pipeline Syntax, as highlighted in the diagram above, a new tab opens up in the browser. This is a handy utility where we can specify the operation that we wish to perform, and the tool will generate the script in Groovy for us. We can then copy the script and paste it into the pipeline configuration.

点击Pipeline Syntax(如上图所示),在浏览器中会打开一个新的标签。这是一个方便的工具,我们可以指定我们想要执行的操作,该工具将为我们生成Groovy脚本。然后我们可以复制该脚本并将其粘贴到管道配置中。

Let’s select checkout: General SCM in the Sample Step drop-down. After providing the SCM Repo URL and user credentials, we need to click the Generate Pipeline Script button.

让我们选择结账。一般SCM样本步骤下拉中。在提供SCM Repo URL和用户凭证后,我们需要点击Generate Pipeline Script按钮。

This generates the script in the text box:

这就在文本框中生成了脚本。

Let’s copy this script and save it somewhere for later use.

让我们复制这个脚本,并把它保存在某个地方供以后使用。

On the same page, let’s scroll up and select withMaven: Provide Maven environment in the Sample Step drop-down. It must be noted here, that this option will be available only if Pipeline Maven Integration Plugin is installed.

在同一页,让我们向上滚动,选择withMaven。在示例步骤下拉菜单中选择提供Maven环境。必须注意的是,只有在安装了Pipeline Maven集成插件的情况下才能使用该选项

We need to select the names of Maven and JDK installations next to the corresponding drop-downs. We need to click the Generate Pipeline Script button.

我们需要在相应的下拉列表中选择Maven和JDK的安装名称。我们需要点击Generate Pipeline Script按钮。

This generates the script in the text box:

这就在文本框中生成了脚本。

Let’s save the script.

我们来保存脚本。

There are still a few more scripts that we need to generate. Let’s select node: Allocate node in the Sample Step drop-down, type master in the Label text field and click Generate Pipeline Script:

还有一些我们需要生成的脚本。让我们选择节点。在样本步骤下拉中选择分配节点,在标签文本字段中输入,然后点击生成管道脚本

Let’s save the script.

我们来保存脚本。

And last one.

还有最后一个。

Let’s select stage: Stage in the Sample Step drop-down, type scm in the Stage Name text field and click Generate Pipeline Script:

让我们选择stage。阶段样本步骤下拉中,在阶段名称文本字段中输入scm,然后单击生成管道脚本

Let’s save it.

让我们来拯救它。

It’s time to collate all the scripts generated so far and stitch them together:

现在是时候整理迄今为止产生的所有脚本,并将它们缝合起来。

node('master') {
    stage('scm') {
        checkout([$class: 'GitSCM', 
          branches: [[name: '*/master']], 
          doGenerateSubmoduleConfigurations: false, 
          extensions: [], 
          submoduleCfg: [], 
          userRemoteConfigs: [[credentialsId: 'e50f564f-fbb7-4660-9c95-52dc93fa26f7', 
          url: 'https://developer@bitbucket.org/projects/springpocrepo.git']]])
    }

    stage('build') {
        withMaven(jdk: 'JDK9.0.1', maven: 'Maven3.5.2') {
            sh 'mvn clean install'
        }
    }
}

The first statement, node(‘master’) in the script above, indicates that the job will be executed on a node named master, which is the default node on the Jenkins server.

上面脚本中的第一条语句,node(‘master’) 表示作业将在名为master的节点上执行,该节点是Jenkins服务器上的默认节点。

Let’s copy the above script to the Text Box in Pipeline section:

让我们把上述脚本复制到Pipeline部分的文本框中。

Let’s save this configuration.

让我们保存这个配置。

Now, there’s only one thing that’s left out. We need to configure a Webhook in Bitbucket. The Webhook is responsible for sending out a push notification to Jenkins server, whenever a particular event takes place in Bitbucket.

现在,只有一件事没有做了。我们需要在Bitbucket中配置一个Webhook。Webhook负责在Bitbucket中发生特定事件时向Jenkins服务器发送推送通知

Let’s take a look at how to configure it.

让我们来看看如何配置它。

Let’s log in to Bitbucket and select a repository. We should see an option Settings on the left-hand side column. Let’s click it, and we should see an option Webhooks in WORKFLOW section. Let’s create a new Webhook.

让我们登录Bitbucket并选择一个版本库。我们应该在左侧栏中看到一个选项Settings。让我们点击它,我们应该在WORKFLOW部分看到一个选项Webhooks。让我们创建一个新的Webhook。

We need to provide some name to this webhook in the Title field. We also need to provide a URL for the webhook in the URL field. This URL needs to point to one particular REST API Endpoint provided by Jenkins, and that endpoint is bitbucket-hook.

我们需要在Title字段中为这个webhook提供一些名称。我们还需要在URL字段中为该webhook提供一个URL。这个URL需要指向Jenkins提供的一个特定的REST API端点,这个端点就是bitbucket-hook

It must be noted that the URL MUST end with a trailing slash:

必须注意,URL必须以尾部斜线结尾

 

While configuring the Webhook above, we’ve selected option Repository push. This means Bitbucket will send a notification to Jenkins server whenever a push happens.

在配置上面的Webhook时,我们选择了选项Repository push这意味着只要有推送发生,Bitbucket就会向Jenkins服务器发送通知

This behavior can be modified; there are several different options to choose from.

这种行为可以被修改;有几个不同的选项可以选择。

For now, let’s go with the default option,i.e., Repository Push.

现在,让我们使用默认选项,即Repository Push

We can setup webhook in Github, too; here‘s some helpful information on how to configure that.

我们也可以在Github中设置webhook,这里有一些关于如何配置的有用信息。

Long story short: we’ve created a pipeline script in Groovy language – that should pull the source code from the master branch of the provided SCM repository (using the provided user credentials), whenever there’s a push in the repository and then execute mvn clean install command on the Jenkins server.

长话短说:我们用Groovy语言创建了一个管道脚本–应该从所提供的SCM仓库的主分支拉取源代码(使用所提供的用户凭证),每当仓库中有一个推送,然后在Jenkins服务器上执行mvn clean install命令

It must be noted that this job’s not going to run at any particular time. Instead, it’s going to wait till there’s a push in the master branch of the SCM repository.

必须注意的是,这个工作不会在任何特定时间运行。相反,它将等待SCM仓库的主分支有推送。

As soon as there’s a new push event, we’ll see a new execution in the “Build History” section on the Jenkins job dashboard.

只要有一个新的推送事件,我们就会在Jenkins作业仪表板上的“Build History”部分看到一个新的执行。

We should see a new build being initiated with a pending status next to it.

我们应该看到一个新的构建正在启动,旁边有一个pending状态。

In a few seconds, this build should start execution, and we’ll be able to see the complete log in Console Output.

几秒钟后,这个构建应该开始执行,我们将能够在控制台输出中看到完整的日志。

The first statement in the console output says “Started by Bitbucket push by..” – this means that the build was triggered automatically when a Push took place in Bitbucket:

控制台输出中的第一句话是 “由Bitbucket推送开始…”-这意味着当Bitbucket发生推送时,构建被自动触发了。

 

If all goes well, the build should complete successfully.

如果一切顺利,构建应该成功完成。

6. Create a Job That Uses Jenkinsfile

6.创建一个使用Jenkinsfile的工作

It’s possible NOT to write any script in the Jenkins pipeline and still achieve build execution being triggered by the Bitbucket Webhook.

在Jenkins管道中不写任何脚本也可以实现由Bitbucket Webhook触发的构建执行。

To do so, we have to create a new file in Bitbucket and name it as Jenkinsfile. The pipeline script needs to be transferred to this Jenkinsfile with a slight modification. Let’s see exacttly how to do that.

为此,我们必须在Bitbucket创建一个新文件,并将其命名为Jenkinsfile。管道脚本需要被转移到这个Jenkinsfile中,并稍作修改。让我们看看具体怎么做。

We’ll create a new pipeline in Jenkins and name it PipelineWithJenkinsfile.

我们将在Jenkins中创建一个新的管道,命名为PipelineWithJenkinsfile

On the pipeline configuration page, we’ll select Pipeline script from SCM next to Definition in the Pipeline section. We’ll see a drop-down with different options next to SCM. Let’s choose Git from the drop-down.

在管道配置页面,我们将在Pipeline部分的Definition旁边选择Pipeline script from SCM>。我们会看到SCM旁边有一个下拉的不同选项。让我们从下拉菜单中选择Git

We then have to provide the URL of Bitbucket repository and user credentials. Let’s ensure that the text field next to Script Path contains the default value,i.e., Jenkinsfile:

然后我们必须提供Bitbucket仓库的URL和用户凭证。让我们确保Script Path旁边的文本字段包含默认值,即Jenkinsfile

 

As far as Jenkins is concerned, that’s all we need to configure.

就Jenkins而言,这就是我们需要配置的全部内容。

However, we have to create the Jenkinsfile in the repository; so, let’s create a new text file, name it as Jenkinsfile and use this simple groovy script:

然而,我们必须在版本库中创建Jenkinsfile;因此,让我们创建一个新的文本文件,命名为Jenkinsfile并使用这个简单的groovy脚本。

node('master') {
    stage('scm') {
        checkout scm
    }
    stage('build') {
        withMaven(jdk: 'JDK9.0.1', maven: 'Maven3.5.2') {
            sh 'mvn clean install'
        }
    }
}

This script is almost the same as the pipeline script that we created in the earlier section, with just one modification. The statement in stage(‘scm’) doesn’t need the URL and user credentials information. Instead, all it needs is checkout scm.

这个脚本与我们在前面章节中创建的管道脚本几乎一样,只是做了一个修改。stage(‘scm’)中的语句不需要URL和用户凭证信息。相反,它所需要的是checkout scm

And that’s it. The moment we commit this file into Bitbucket, it’ll trigger the build in Jenkins – and we should see the build being triggered in the Build History.

就这样了。当我们把这个文件提交到Bitbucket时,它将在Jenkins中触发构建 – 我们应该在Build History中看到构建被触发。

The only difference between this section and the earlier one is that we defined the pipeline script in the Bitbucket repository.

本节与之前的唯一区别是,我们在Bitbucket仓库中定义了管道脚本。

So, the build script is part of the source code of the project that needs to be built. We’re not maintaining the script in Jenkins itself.

所以,构建脚本是需要构建的项目的源代码的一部分。我们没有在Jenkins中维护这个脚本本身。

Instead, Jenkins has knowledge of the SCM repository details and the script file. Whenever there is a push to this repository, the script in Jenkinsfile gets executed on the Jenkins server.

相反,Jenkins知道SCM版本库的细节和脚本文件。每当有一个推送到这个仓库,Jenkinsfile中的脚本就会在Jenkins服务器上执行

7. Conclusion

7.结论

In this tutorial, we’ve seen how jobs can be configured and scheduled in Jenkins using various strategies.

在本教程中,我们已经看到了如何使用各种策略在Jenkins中配置和调度作业。

We’ve also seen how to configure a job in Jenkins so that it’s automatically triggered, based on certain actions performed in SCM repository such as Bitbucket.

我们也看到了如何在Jenkins中配置一个作业,以便根据SCM仓库(如Bitbucket)中的某些操作自动触发。