Trigger Kubernetes CronJob manually from Java using YAKC


Introduction

In this post, I’ll show you how to perform the equivalent to kubectl --from=cronjob/<cronjob-name> <job-name> (manual trigger) from Java using YAKC- Yet Another Kubernetes Client.

This performs something similar to what the official Kubernetes Dashboard CronJob trigger action does.

A screenshot of Kubernetes Dashboard: Trigger CronJob manually

CronJob manual trigger

Once you’ve deployed a CronJob to your cluster, in most cases it makes sense to trigger a test run. You probably need to check that everything works fine without having to wait for the scheduled time.

Starting at version 1.10, Kubernetes offers a way to create a Job from a CronJob using kubectl. This basically translates into manually triggering the CronJob.

Following is the code implementation in Kubectl:

In the previous code snippet, we see how kubectl creates a new Job using the CronJob’s JobTemplate and propagates the labels.

Trigger CronJob from Java

Now that we’ve seen how kubectl creates a Job from a CronJob, let’s see how we can achieve this with YAKC.

The previous code snippet is part of the CronJobs jbang quickstart.

The first step is to retrieve the actual CronJob from the cluster. Next, we generate a random name for the manually triggered job using the CronJob’s name as the prefix.

Finally, we create a new Job using the retrieved CronJob’s JobTemplateSpec and propagate its labels. We also add an owner reference to the created Job so that it can be associated and listed when querying the CronJob.

Since this example is hosted as a jbang script, you can test it by running the following command:

Following you can check the operation result in YAKC – Kubernetes Dashboard interface (you can read more about this project here):

YAKC Kubernetes Dashboard CronJob manual trigger demo

Conclusion

In this post, I’ve shown you how to manually trigger CronJobs from Java using YAKC.

I’ve extracted the code for this post from the jbang quickstart section of YAKC. You can learn more by visiting  YAKC’s GitHub project site. You can also see related code here.

Leave a comment

Your email address will not be published. Required fields are marked *