# How to run Cron jobs in Java?

To run Cron jobs in Java, you can use the Quartz Scheduler library. Here are the steps to create and schedule a Java program using Quartz Scheduler:

[info]
## 🔭 Want to get alerted when your Cron doesn’t run correctly?
Go to [Better Stack](https://betterstack.com/uptime/) and start monitoring in 5 minutes.
[/info]

## Add Quartz dependency

You need to add the Quartz dependency in your Java project. You can add the following dependency to your Maven pom.xml file:

```xml
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.2</version>
</dependency>
```

## Create a Job

Create a Java class that implements the `Job` interface. For example, let's say you want to print `"Hello world!"` every minute. You can create a Job called `HelloJob` with the following code:

```java
public class HelloJob implements Job {
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("Hello world!");
    }
}
```

## Create a Trigger

Create a Trigger that specifies when the Job should run. For example, to run the `HelloJob` every minute, you can create a Trigger with the following code:

```java
Trigger trigger = TriggerBuilder.newTrigger()
        .withIdentity("trigger1", "group1")
        .withSchedule(CronScheduleBuilder.cronSchedule("0 * * ? * *"))
        .build();
```

This code creates a Trigger that runs the `HelloJob` every minute using a Cron expression.

## Create a Scheduler

Create a Scheduler that schedules the Job and Trigger. For example, you can create a Scheduler with the following code:

```java
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

JobDetail job = JobBuilder.newJob(HelloJob.class)
        .withIdentity("job1", "group1")
        .build();

scheduler.scheduleJob(job, trigger);

scheduler.start();
```

This code creates a Scheduler that schedules the `HelloJob` with the specified Trigger.

## Verify the Job

You can verify that the Job is running by checking the output of the Java program. You should see `"Hello world!`" printed to the console every minute.

By following these steps, you can create and schedule a Java program to run as a Cron job using the Quartz Scheduler library.

[ad-uptime]