背景

Jenkins是很常见的任务调度服务。在界面上可以取消正在执行和正在排队的任务。
但是,Jenkins Java API只提供了停止运行中的任务,并没有提供取消队列中的任务的方法。

如何解决

Jenkins其实可以执行groovy脚本,Jenkins Java API提供了执行脚本的接口。
下面是代码,判断逻辑仅供参考。注意编码和代码格式。。
简单说就是拿到jenkins所有排队中任务,然后通过jobname过滤,然后想精确到某个任务可以在任务里通过判断任务的参数来确定:比如唯一的ID。

fun JenkinsServer.cancelTaskInQueue(jobName: String, p1: String, p2: String, p3: String){
    runScript(runScriptHtml(jobName, URLEncoder.encode("import hudson.model.*\n" +
            " \n" +
            "def q = Jenkins.instance.queue\n" +
            "q.items.findAll { \n" +
            "  \n" +
            "  it.task.name.startsWith(\"${jobName}\")\n" +
            "  \n" +
            "}.each { \n" +
            "  p1=\"\"\n" +
            "  p2=\"\"\n" +
            "  p3=\"\"\n" +
            "  it.params.eachLine{\n" +
            "    aa = it.split(\"=\")\n" +
            "    \n" +
            "    if(aa[0].equals(\"p1\")){\n" +
            "      if(aa.length == 2){\n" +
            "      \tp1 = aa[1]\n" +
            "      }\n" +
            "    }\n" +
            "    if(aa[0].equals(\"p2\")){\n" +
            "      if(aa.length == 2){\n" +
            "      \tp2 = aa[1]\n" +
            "      }\n" +
            "    }\n" +
            "    if(aa[0].equals(\"p3\")){\n" +
            "      if(aa.length == 2){\n" +
            "      \tp3 = aa[1]\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "  if(\"${p1}\".equals(p1) && \"${p2}\".equals(p2) && \"${p3}\".equals(p3)){\n" +
            "    println(\"cancel auto build ${p1}:${p2} is ${p3}\")\n" +
            "    q.cancel(it);\n" +
            "  }\n" +
            "}\n" +
            "\n", "UTF-8")))
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐