### Basic MultiClusterWebServer Setup Source: https://www.jobrunr.io/en/documentation/pro/jobrunr-pro-multi-dashboard Starts a MultiClusterWebServer with default configuration. Access the dashboard at localhost:8000. ```java var multiClusterWebServer = new MultiClusterWebServer(); multiClusterWebServer.start(); ``` -------------------------------- ### Example Mail Service Class Source: https://www.jobrunr.io/en/documentation/background-methods/background-jobs-dependencies This is an example of a service class that might be used within a background job. It demonstrates dependency injection through its constructor. ```java @Component public class MailService { private EmailRenderer emailRenderer; private UserRepository userRepository; private Environment environment; public MailService(EmailRenderer emailRenderer, UserRepository userRepository, Environment environment) { this.emailRenderer = emailRenderer; this.userRepository = userRepository; this.environment = environment; } public void sendMail(UUID userId, String templateId) { User user = userRepository.getById(userId); String htmlEmail = emailRenderer.renderEmail(user, templateId); sendMail(user.getEmailAddress(), htmlEmail); } private void sendMail(String to, String htmlContent) { Session session = Session.getInstance(prop, null); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(env.getProperty("mail.from"))); message.setRecipients( Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(env.getProperty("mail.subject")); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(htmlContent, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); message.setContent(multipart); Transport.send(message); } private Properties getSmtpProperties() { Properties prop = new Properties(); prop.put("mail.smtp.host", env.getProperty("smtp.host")); prop.put("mail.smtp.port", "25"); return prop; } } ``` -------------------------------- ### CustomSchedule Implementation Example Source: https://www.jobrunr.io/en/documentation/background-methods/recurring-jobs Example implementation of a CustomSchedule for a recurring job that runs daily but every half hour during weekends. ```java public class MySchedule extends CustomSchedule { private final CronExpression everyHalfHour = new CronExpression(Cron.everyHalfHour()); private final CronExpression daily = new CronExpression(Cron.daily()); @Override public Instant next(Instant createdAtInstant, Instant currentInstant, ZoneId zoneId) { var day = currentInstant.atZone(zoneId).getDayOfWeek(); if(day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY) { return everyHalfHour.next(createdAtInstant, currentInstant, zoneId); } return daily.next(createdAtInstant, currentInstant, zoneId); } @Override public String asString() { return CustomSchedule.expressionFor(MySchedule.class, ""); } } ``` -------------------------------- ### Configure JobRunr with In-Memory Storage Source: https://www.jobrunr.io/en/documentation/5-minute-intro Configure JobRunr to use in-memory storage, a job activator, a background job server, and the dashboard. This is a basic setup for getting started. ```java JobRunr.configure() .useJobActivator(applicationContext::getBean) .useStorageProvider(new InMemoryStorageProvider()) .useBackgroundJobServer() .useDashboard() .initialize(); ``` -------------------------------- ### Implement JobClientFilter and JobServerFilter Source: https://www.jobrunr.io/en/documentation/pro/job-filters Implement `JobClientFilter` and `JobServerFilter` to create custom job filters. This example shows how to send Slack notifications for a specific job. ```java @Component public class NotifyJobCreatedFilter implements JobClientFilter, JobServerFilter { private SlackNotificationService slackNotificationService; public NotifyJobCreatedFilter(SlackNotificationService slackNotificationService) { this.slackNotificationService = slackNotificationService; } void onCreated(Job job) { if("Monthly Stripe Report".equals(job.getJobName())) { slackNotificationService.sendNotification("#accounting-team", "Monthly Stripe Report is being generated"); } } void onProcessingSucceeded(Job job) { if("Monthly Stripe Report".equals(job.getJobName())) { slackNotificationService.sendNotification("#accounting-team", "Monthly Stripe Report is generated."); } } void onProcessingFailed(Job job, Exception e) { if("Monthly Stripe Report".equals(job.getJobName())) { // optional logging that the job failed. Not sending a notification as Job will still be retried } } void onFailedAfterRetries(Job job) { if("Monthly Stripe Report".equals(job.getJobName())) { Optional lastJobStateOfType = job.getLastJobStateOfType(FailedState.class); String exceptionMessage = lastJobStateOfType.map(s -> s.getException().getMessage()).orElse("Unknown exception"); slackNotificationService.sendNotification("#support-team", "Error generating Monthly Stripe Report." + exceptionMessage); } } } ``` -------------------------------- ### Enqueue a Background Job Source: https://www.jobrunr.io/en/documentation This is a basic example of how to enqueue a fire-and-forget background job. The lambda is serialized and stored in the database, and execution returns immediately. ```java BackgroundJob.enqueue(() -> emailService.sendWelcomeEmail(userEmail)); ``` -------------------------------- ### Job State Metrics Query Example Source: https://www.jobrunr.io/en/documentation/configuration/metrics The `jobrunr.jobs.by-state` metric can be queried with a state tag to filter results. This example shows how to retrieve succeeded jobs. ```http http://localhost:8080/actuator/metrics/jobrunr.jobs.by-state?tag=state:SUCCEEDED ``` -------------------------------- ### Defining a Complex Workflow with Scheduled Continuations Source: https://www.jobrunr.io/en/documentation/pro/batches This example illustrates creating complex workflows by scheduling jobs and chaining continuations. Step 1B is scheduled to run tomorrow, and Step 1C will run only after Step 1B succeeds. ```java public void aComplexWorkflow() { String campaignReportLocation = "/path/to/campaign/report/" + campaignId + ".csv"; BackgroundJob .startBatch(this::step1) .continueWith(() -> System.out.println("Step 2 which will only run after Step 1 completely succeeded")); } public void step1() { BackgroundJob.enqueue(() -> System.out.println("Step 1A of batch")); BackgroundJob .schedule(() -> System.out.println("Step 1B of batch which will run tomorrow"), now().add(24, HOURS)) .continueWith(() -> System.out.println("Step 1C of batch which will run just after Step 1B has succeeded")); } ``` -------------------------------- ### List of Background Job Server Metrics Source: https://www.jobrunr.io/en/documentation/configuration/metrics These metrics provide insights into the health and resource usage of the JobRunr background job server. No specific setup is required beyond enabling the feature. ```text jobrunr.background-job-server.first-heartbeat jobrunr.background-job-server.last-heartbeat jobrunr.background-job-server.poll-interval-in-seconds jobrunr.background-job-server.process-all-located-memory jobrunr.background-job-server.process-cpu-load jobrunr.background-job-server.process-free-memory jobrunr.background-job-server.system-cpu-load jobrunr.background-job-server.system-free-memory jobrunr.background-job-server.system-total-memory jobrunr.background-job-server.worker-pool-size ``` -------------------------------- ### Configure Custom License Key Provider Source: https://www.jobrunr.io/en/documentation/pro/installation Configure JobRunr Pro to use a custom license key provider during background job server setup. This allows for custom license management logic. ```java JobRunrPro .configure() // ... .useBackgroundJobServer(usingStandardBackgroundJobServerConfiguration() .andLicenseKeyProvider(new MyCustomLicenseKeyProvider()) ) // ... ``` -------------------------------- ### Manual JobActivator Configuration (Spring) Source: https://www.jobrunr.io/en/documentation/background-methods/background-jobs-dependencies This example shows how to manually configure a JobActivator bean in a Spring application context, using a method reference to ApplicationContext::getBean. ```java @Bean public BackgroundJobServer backgroundJobServer(StorageProvider storageProvider, JobActivator jobActivator) { BackgroundJobServer backgroundJobServer = new BackgroundJobServer(storageProvider, jobActivator); backgroundJobServer.start(); return backgroundJobServer; } @Bean public JobActivator jobActivator(ApplicationContext applicationContext) { return applicationContext::getBean; } ``` -------------------------------- ### Configure ExposedTransactionAwareConnectionProvider as a Spring Bean Source: https://www.jobrunr.io/en/documentation/pro/transactions This example shows how to provide an ExposedTransactionAwareConnectionProvider as a Spring Bean. JobRunr Pro automatically configures the plugin if Exposed is on the classpath when using a Spring Boot starter. ```java @Bean(name = "connectionProvider") public ConnectionProvider getExposedTransactionAwareConnectionProvider() { return new ExposedTransactionAwareConnectionProvider(); } ``` -------------------------------- ### JobRunr Pro Dashboard Authentication with Fluent API Source: https://www.jobrunr.io/en/documentation/pro/sso-authentication Configure JobRunr Pro dashboard authentication using the Fluent API and an OpenIdConnectSettings object. This approach allows programmatic setup of SSO. ```java OpenIdConnectSettings openIdConnectSettings = new OpenIdConnectSettings( "your-well-known-openid-configuration-url", "client-id", "client-secret", "scope", Set.of("acceptedAudience") ); JobRunrPro .configure() // ... .useDashboard(usingStandardDashboardConfiguration() // ... .andAuthentication(new OpenIdConnectAuthenticationProvider(openIdConnectSettings)) ) ``` -------------------------------- ### Configure Micrometer Integration with Fluent API Source: https://www.jobrunr.io/en/documentation/configuration/metrics Use this fluent API to configure Micrometer metrics integration when not using Spring Actuator or for custom registry setup. Ensure a MeterRegistry is available. ```java JobRunr.configure() // ... other config .useMicroMeter(new JobRunrMicroMeterIntegration(meterRegistry)) ``` -------------------------------- ### Enqueue Job with Multiple Method Calls (Fails) Source: https://www.jobrunr.io/en/documentation/background-methods This example demonstrates an unsupported enqueue operation that results in two jobs. JobRunr only supports enqueuing jobs with a single method call. ```java BackgroundJob.enqueue(() -> { myService.createPDF(); myService.sendPDF(); ); ``` -------------------------------- ### Enqueue a Simple Background Job Source: https://www.jobrunr.io/en/documentation/5-minute-intro Enqueue a basic background job that prints a simple message. This demonstrates the fundamental way to start a job with JobRunr. ```java BackgroundJob.enqueue(() -> System.out.println("Simple!")); ``` -------------------------------- ### Advanced Mutex Usage with Job Parameters Source: https://www.jobrunr.io/en/documentation/pro/mutexes Utilize job parameters to create dynamic mutexes, allowing for finer-grained concurrency control based on specific job inputs. This example creates OS-specific mutexes. ```java public void scanForViruses(File folder) { for(String f : folder.list()) { scanForViruses(f); } } public void scanForViruses(String file) { BackgroundJob.enqueue(() -> osSpecificVirusScan("LINUX", file)); BackgroundJob.enqueue(() -> osSpecificVirusScan("WINDOWS", file)); BackgroundJob.enqueue(() -> osSpecificVirusScan("MACOS", file)); } @Job(mutex = "virus-scanner/%0") public void osSpecificVirusScan(String os, String file) { System.out.println(String.format("This will result in a mutex virus-scanner/%0", os)); } ``` -------------------------------- ### Incorrect Batch Implementation (Lambda within Lambda) Source: https://www.jobrunr.io/en/documentation/pro/batches This example demonstrates an incorrect way to implement batches where the child job enqueueing is done within a lambda passed to `startBatch`. JobRunr cannot analyze lambdas nested within other lambdas, leading to the batch not working as expected. ```java public class NewsletterService { @Inject private UserRepository userRepository; public void sendEmailToAllSubscribers() { BackgroundJob.startBatch(() -> { List users = userRepository.getAllUsers(); for(User user : users) { BackgroundJob.enqueue(() -> mailService.send(user.getId(), "mail-template-key")); } }); } } ``` -------------------------------- ### Configure Delete Policy with Java 8 Lambda Source: https://www.jobrunr.io/en/documentation/pro/custom-delete-policy Use the @Job annotation with deleteOnSuccess to specify when a job moves to the deleted state. This example sets it to 10 minutes. ```java @Job(deleteOnSuccess="PT10M!PT10M") public void startImportingFilesIfPresent() { if(Files.list(importDirectory).findAny()) { BackgroundJob.enqueue(() -> fileImportService.import(Files.list(importDirectory).collect(toList()))); } } ``` -------------------------------- ### Create SQL Tables with DatabaseCreator Source: https://www.jobrunr.io/en/documentation/installation/storage Use the DatabaseCreator class to create necessary SQL tables. This requires a user with DDL rights and the JDBC driver. ```bash java -cp jobrunr-8.6.1.jar org.jobrunr.storage.sql.common.DatabaseCreator {jdbcUrl} {userName} {password} ``` -------------------------------- ### URL-based License Key Provider Configuration (Java) Source: https://www.jobrunr.io/en/documentation/pro/installation Configure JobRunr Pro to use a URL to dynamically fetch the license key using the UrlLicenseKeyProvider. ```java JobRunrPro .configure() // ... .useBackgroundJobServer(usingStandardBackgroundJobServerConfiguration() .andLicenseKeyProvider("https://example.com/license-key") ) // ... ``` -------------------------------- ### Generate SQL Scripts for Manual Application Source: https://www.jobrunr.io/en/documentation/pro/database-migrations Execute the `DatabaseSqlMigrationFileProvider` command to generate all necessary database-related SQL scripts. These scripts can then be manually applied to set up or update your database schema. ```bash java -cp jobrunr-${jobrunr.version}.jar org.jobrunr.storage.sql.common.DatabaseSqlMigrationFileProvider {databaseType} ({tablePrefix}) ``` -------------------------------- ### Job with InterruptedException Source: https://www.jobrunr.io/en/documentation/background-methods/deleting-jobs This example shows a method that throws InterruptedException, which JobRunr can handle gracefully when a job is deleted during processing. ```java public void doWorkThatTakesLong(int seconds) throws InterruptedException { TimeUnit.SECONDS.sleep(seconds); System.out.println("WORK IS DONE!!!!!!!!"); } ``` -------------------------------- ### Advanced JobRunr Configuration with Fluent API Source: https://www.jobrunr.io/en/documentation/configuration/fluent Demonstrates advanced JobRunr configuration using the fluent API. This includes conditional enabling of the background job server and dashboard, setting worker counts, custom filters, and integrating with Micrometer. ```java boolean isBackgroundJobServerEnabled = true; // or get it via ENV variables boolean isDashboardEnabled = true; // or get it via ENV variables JobRunr.configure() .useJobActivator(jobActivator) .useJobStorageProvider(jobStorageProvider) .withJobFilter(new RetryFilter(2)) // only do two retries by default .useBackgroundJobServerIf(isBackgroundJobServerEnabled, usingStandardBackgroundJobServerConfiguration().andWorkerCount(4)) // only use 4 worker threads (extra options available) .useDashboardIf(isDashboardEnabled, 80) // start on port 80 instead of 8000 .useJmxExtensions() .useMicroMeter(new JobRunrMicroMeterIntegration(meterRegistry)) .initialize(); ``` -------------------------------- ### Generate Flyway/Liquibase SQL Scripts Source: https://www.jobrunr.io/en/documentation/pro/database-migrations Use the `DatabaseSqlMigrationFileProvider` command-line tool to generate SQL scripts for Flyway or Liquibase. Specify the database type, and optionally table prefix, database manager, and output directory. ```bash java -cp jobrunr-${jobrunr.version}.jar org.jobrunr.storage.sql.common.DatabaseSqlMigrationFileProvider {databaseType} (-DtablePrefix=...) (-DdatabaseManager=...) (-Doutput=...) where: - databaseType is one of 'cockroach', 'db2', 'h2', 'mariadb', 'mysql', 'oracle', 'postgres', 'sqlite', 'sqlserver' - databaseManager is one of 'none', 'liquibase', 'flyway' (defaults to none) - output is the directory where to create the requested files (defaults to current directory) ``` -------------------------------- ### Configure Default Retry Policy Source: https://www.jobrunr.io/en/documentation/background-methods/dealing-with-exceptions Override the default RetryFilter to set a custom number of retries for all jobs. This example sets the retry count to 2. ```java JobRunr.configure() .withJobFilters(new RetryFilter(2)) .useBackgroundJobServer(new BackgroundJobServer(...)) .... ``` -------------------------------- ### URL-based License Key Provider Configuration (Properties) Source: https://www.jobrunr.io/en/documentation/pro/installation Configure JobRunr Pro to use a URL to dynamically fetch the license key via application properties. ```properties jobrunr.license-key=https://example.com/license-key ``` -------------------------------- ### URL-based License Key Provider Configuration (YAML) Source: https://www.jobrunr.io/en/documentation/pro/installation Configure JobRunr Pro to use a URL to dynamically fetch the license key via YAML configuration. ```yaml jobrunr: license-key: https://example.com/license-key ``` -------------------------------- ### Configure Retries Per Job in JobRequestHandler Source: https://www.jobrunr.io/en/documentation/background-methods/dealing-with-exceptions Configure the number of retries for a job within its JobRequestHandler using the @Job annotation. This example sets retries to 2. ```java @Job(name="Job Name", retries=2) public void run(MyJobRequest myJobRequest) { System.out.println("I will only be retried two times "); } ``` -------------------------------- ### Schedule Recurring Job using JobRequestScheduler Bean Source: https://www.jobrunr.io/en/documentation/background-methods/recurring-jobs Schedules a recurring job using the JobRequestScheduler bean, which is useful for creating job requests. This example uses Cron.daily() and a SysOutJobRequest. ```java @Inject private JobRequestScheduler jobRequestScheduler; jobRequestScheduler.scheduleRecurrently(Cron.daily(), new SysOutJobRequest("Easy!")); ``` -------------------------------- ### Configure Dashboard Port with Fluent API Source: https://www.jobrunr.io/en/documentation/background-methods/dashboard Use this fluent configuration to enable the dashboard and specify the port it should run on. ```java JobRunr.configure() .useDashboard(8000) ``` -------------------------------- ### Configure Retries Per Job with @Job Annotation Source: https://www.jobrunr.io/en/documentation/background-methods/dealing-with-exceptions Set the number of retries for a specific job using the 'retries' attribute in the @Job annotation. This example limits retries to 2. ```java @Job(name="Job Name", retries=2) public void doWorkWithCustomJobFilters() { System.out.println("I will only be retried two times "); } ``` -------------------------------- ### Gradle Repository and Dependency Configuration Source: https://www.jobrunr.io/en/documentation/pro/installation Configure your Gradle project to use the JobRunr Pro private Maven repository and add the starter dependency. ```gradle repositories { mavenCentral() maven { url "https://repo.jobrunr.io/private-releases" credentials { username "${jobrunrProAccess.userName}" password "${jobrunrProAccess.password}" } } } dependencies { implementation 'org.jobrunr:jobrunr-pro-spring-boot-3-starter:8.6.1' } ``` -------------------------------- ### Create Recurring Job with Builder Pattern Source: https://www.jobrunr.io/en/documentation/background-methods/recurring-jobs Creates a recurring job using the builder pattern, allowing for a more fluent and readable way to configure job schedules. This example uses Cron.daily(). ```java @Inject private JobScheduler jobScheduler; jobScheduler.createRecurrently(aRecurringJob() .withCron(Cron.daily()) .withJobLambda(() -> System.out.println("I'm created by the builder!"))); ``` -------------------------------- ### Configure Server Tags with Fluent API Source: https://www.jobrunr.io/en/documentation/pro/server-tags Configure server tags for a background job server using the fluent API. Pass all desired server tags as strings to the `andTags` method. ```java JobRunrPro .configure() .useBackgroundJobServer(usingStandardBackgroundJobServerConfiguration().andTags(LINUX, MACOS)) ... ``` -------------------------------- ### Configure JobRunr in application.properties Source: https://www.jobrunr.io/en/documentation/configuration/quarkus Enable the background job server and dashboard by setting properties in your application.properties file. These are disabled by default. ```properties quarkus.jobrunr.background-job-server.enabled=true quarkus.jobrunr.dashboard.enabled=true ``` -------------------------------- ### Configure JobRunr in application.yml Source: https://www.jobrunr.io/en/documentation/configuration/micronaut Enable the background job server and dashboard by setting the respective properties to `true` in your `application.yml` file. These are disabled by default. ```yaml jobrunr: background-job-server: enabled: true dashboard: enabled: true ``` -------------------------------- ### Define DoNotRetry Policy (Spring Bean) Source: https://www.jobrunr.io/en/documentation/background-methods/dealing-with-exceptions Configure a policy to prevent retries for specific exceptions or jobs. This example uses PerJobRetryPolicy with DoNotRetryPolicy for MyIllegalStateException and jobs containing 'Cache update' in their name. ```java @Bean public RetryPolicy myCustomRetryPolicy() { return new PerJobRetryPolicy( new ExponentialBackoffRetryPolicy(), // default policy if no per job policy matches new DoNotRetryPolicy().ifException(e -> e instanceof MyIllegalStateException), new DoNotRetryPolicy().ifJob(job -> job.getName().contains("Cache update")) ); } ``` -------------------------------- ### Generate SQL Migration Scripts Source: https://www.jobrunr.io/en/documentation/installation/storage Generate SQL scripts for your database to manually apply. Specify the database type and an optional table prefix. ```bash java -cp jobrunr-8.6.1.jar org.jobrunr.storage.sql.common.DatabaseSqlMigrationFileProvider {databaseType} ({tablePrefix}) ``` -------------------------------- ### Retrieve Previous Job Result in a Chain Source: https://www.jobrunr.io/en/documentation/pro/job-chaining Use JobContext to get the ID of the previously executed job and StorageProvider to retrieve the job and its result. This is useful when a subsequent job needs data from an earlier one. ```java public void notifyViaSlack(JobContext context) { var awaitedJobId = context.getAwaitedJobId(); // can be null if this job has no ancestor var awaitedJob = storageProvider.getJobById(awaitedJobId); MyJobResult awaitedJobResult = awaitedJob.getResult(); // use the result from the previous job... } ``` -------------------------------- ### Custom License Key Provider with @Singleton Source: https://www.jobrunr.io/en/documentation/pro/installation Implement a custom license key provider using the @Singleton annotation, suitable for environments where singleton beans are managed. ```java @Singleton public LicenseKeyProvider licenseKeyProvider() { return new MyCustomLicenseKeyProvider(); } ``` -------------------------------- ### Configure Delete Policy with JobBuilder Pattern Source: https://www.jobrunr.io/en/documentation/pro/custom-delete-policy Use the JobBuilder pattern to set custom deleteOnSuccess and deleteOnFailure durations for jobs. This example sets success deletion to 1 hour and failure deletion to 8 hours. ```java jobScheduler.create(aJob() .withDeleteOnSuccess(Duration.ofHours(1)) .withDeleteOnFailure(Duration.ofHours(8)) .withJobLambda(() -> System.out.println("This job will move to the deleted state after 1 hour if it succeeded and after 8 hours if it failed."))); ``` -------------------------------- ### Configure Queues using Beans for JobScheduler and Dashboard Source: https://www.jobrunr.io/en/documentation/pro/priority-queues Configure queues by creating a 'Queues' bean and passing it to the JobRunrDashboardWebServer and JobScheduler. This approach is useful for programmatic configuration. ```java @Bean public Queues queues() { return new Queues(defaultQueue, queues); } @Bean public JobRunrDashboardWebServer dashboardWebServer(StorageProvider storageProvider, JsonMapper jsonMapper, Queues queues) { final JobRunrDashboardWebServer jobRunrDashboardWebServer = new JobRunrDashboardWebServer(storageProvider, jsonMapper, queues); jobRunrDashboardWebServer.start(); return jobRunrDashboardWebServer; } @Bean public JobScheduler jobScheduler(StorageProvider storageProvider, Queues queues) { JobScheduler jobScheduler = new JobScheduler(storageProvider, queues); BackgroundJob.setJobScheduler(jobScheduler); return jobScheduler; } ``` -------------------------------- ### Define Per-Exception Custom Retry Policy (Spring Bean) Source: https://www.jobrunr.io/en/documentation/background-methods/dealing-with-exceptions Define a custom retry policy that adapts based on the type of exception thrown. This example uses PerJobRetryPolicy to apply different CustomRetryPolicies for TimeoutException and DatabaseException. ```java @Bean public RetryPolicy myCustomRetryPolicy() { return new PerJobRetryPolicy( new ExponentialBackoffRetryPolicy(), // default policy if no per job policy matches new CustomRetryPolicy(60, 60, 60, 180).ifException(e -> e instanceof TimeoutException), new CustomRetryPolicy(3600).ifException(e -> e instanceof DatabaseException) ); } ``` -------------------------------- ### Configure Dashboard Port with Spring Properties Source: https://www.jobrunr.io/en/documentation/background-methods/dashboard Enable the dashboard and set its port using application properties in a Spring environment. ```properties jobrunr.dashboard.enabled=true jobrunr.dashboard.port=8000 ``` -------------------------------- ### Define Per-Job Custom Retry Policy (Spring Bean) Source: https://www.jobrunr.io/en/documentation/background-methods/dealing-with-exceptions Define a custom retry policy for specific jobs by creating a Bean of type RetryPolicy. This example uses PerJobRetryPolicy to apply different CustomRetryPolicies based on job labels. ```java @Bean public RetryPolicy myCustomRetryPolicy() { return new PerJobRetryPolicy( new ExponentialBackoffRetryPolicy(), // default policy if no per job policy matches new CustomRetryPolicy(3, 4).ifJob(job -> job.getLabels().contains("tenant-A")), new CustomRetryPolicy(9, 10).ifJob(job -> job.getLabels().contains("tenant-B")) ); } ``` -------------------------------- ### Configure JobRunr with PKCE Authentication Source: https://www.jobrunr.io/en/documentation/pro/sso-authentication Use this code to configure JobRunr to use PKCE for authentication by setting the OpenIdClientAuthenticationMode to PKCE. A null value is accepted for the client secret when PKCE is enabled. ```java OpenIdConnectSettings openIdConnectSettings = new OpenIdConnectSettings( "your-well-known-openid-configuration-url", "client-id", null, "scope", OpenIdClientAuthenticationMode.PKCE ); ``` -------------------------------- ### Enable Micrometer Observability Source: https://www.jobrunr.io/en/documentation/pro/observability Enable Micrometer-based observability for JobRunr Pro. This allows for the export of various job-related metrics and timers. ```properties # if you prefer Micrometer jobrunr.jobs.metrics.micrometer-observability.enabled=true ``` -------------------------------- ### Configure Server Tags with Spring Configuration Source: https://www.jobrunr.io/en/documentation/pro/server-tags Set server tags for the background job server in Spring configuration by using the `jobrunr.background-job-server.tags` property. ```properties jobrunr.background-job-server.tags=LINUX,MACOS ``` -------------------------------- ### Configure JobRunr for Microsoft Azure Entra OpenID Source: https://www.jobrunr.io/en/documentation/pro/sso-authentication These properties configure JobRunr to connect with Microsoft Azure Entra for OpenID authentication. Ensure the values for configuration URL, client ID, client secret, and scope are correctly set according to your Azure Entra setup. ```properties jobrunr.dashboard.openid-authentication.openid-configuration-url= # available on Entra Overview Page under endpoints jobrunr.dashboard.openid-authentication.client-id= jobrunr.dashboard.openid-authentication.client-secret= # the client-secret from step 2 jobrunr.dashboard.openid-authentication.scope=openid api:///access_as_user ``` -------------------------------- ### Advanced JobRunr Configuration Options Source: https://www.jobrunr.io/en/documentation/configuration/micronaut Explore all configurable settings for JobRunr, including database, jobs, background job server, dashboard, and miscellaneous options, with their default values. ```yaml jobrunr: database: skip-create: false table_prefix: # allows to set a table prefix (e.g. schema for all tables) datasource: # allows to specify a DataSource specifically for JobRunr type: # if you have multiple supported storage providers available in your application (e.g. an SQL DataSource and MongoDB), it allows to specify which database to choose. Valid values are 'sql', 'mongodb'. jobs: default-number-of-retries:10 #the default number of retries for a failing job retry-back-off-time-seed:3 #the default time seed for the exponential back-off policy. background-job-server: enabled: false worker-count: #this value normally is defined by the amount of CPU's that are available poll-interval-in-seconds: 15 #check for new work every 15 seconds delete-succeeded-jobs-after: 36 permanently-delete-deleted-jobs-after: 72 metrics: enabled: true # Micrometer integration: reports server metrics (cpu usage, memory usage, worker pool size, etc.) dashboard: enabled: false port: 8000 #the port on which to start the dashboard miscellaneous: allow-anonymous-data-usage: true #this sends the amount of succeeded jobs for marketing purposes ``` -------------------------------- ### Configure JobRunr Pro with Auto-Discovery Source: https://www.jobrunr.io/en/documentation/pro/jobrunr-pro-multi-dashboard Enable auto-discovery for JobRunr Pro clusters by adding the `andAutoDiscovery()` method to the dashboard configuration. This allows clusters to announce themselves to the multi-cluster web server. ```java JobRunrPro .configure() // .use... your usual config .useDashboard(usingStandardDashboardConfiguration() .andPort(9000) // .and... your usual dashboard web server config .andApiKey("my-api-key").andAutoDiscovery("https://multi-cluster.acme.com/multi", "Order fulfillment service") ``` -------------------------------- ### Configure Weighted Round Robin Dynamic Queues with Fluent API Source: https://www.jobrunr.io/en/documentation/pro/dynamic-queues Configure weighted round robin dynamic queues using the Fluent API, specifying a label prefix and a map of tenant weights. This allows certain queues to receive proportionally more resources. ```java JobRunrPro.configure() .useStorageProvider(SqlStorageProviderFactory.using(dataSource)) .useBackgroundJobServer(usingStandardBackgroundJobServerConfiguration() .andWorkerCount(100) .andDynamicQueuePolicy(new WeightedRoundRobinDynamicQueuePolicy("tenant:", Map.of("Tenant-A", 5)))) .useDashboard(usingStandardDashboardConfiguration() .andDynamicQueueConfiguration("Tenants", "tenant:")) .initialize(); ``` -------------------------------- ### Sending Emails to All Subscribers (Old Way) Source: https://www.jobrunr.io/en/documentation/pro/batches This code demonstrates the traditional approach to sending emails to all subscribers without using JobRunr Pro's batch functionality. It directly enqueues each email sending job. ```java public class NewsletterService { @Inject private UserRepository userRepository; public void sendEmailsToAllSubscribers() { List users = userRepository.getAllUsers(); for(User user : users) { BackgroundJob.enqueue(() -> mailService.send(user.getId(), "mail-template-key")); } } } ``` -------------------------------- ### Configure Processing Application with Fluent API Source: https://www.jobrunr.io/en/documentation/configuration/fluent Sets up the JobRunr configuration for a processing application. It uses SQL storage and enables the background job server and JMX extensions. Ensure the HikariCP configuration matches the enqueueing application. ```java public class ProcessingApplication { public static void main(String[] args) { HikariConfig config = new HikariConfig(); config.setJdbcUrl(""); config.setUsername(""); config.setPassword(""); HikariDataSource dataSource = new HikariDataSource(config); JobRunrPro.configure() .useStorageProvider(SqlStorageProviderFactory.using(dataSource)) .useBackgroundJobServer() .useJmxExtensions() .initialize(); } } ``` -------------------------------- ### Enable OpenTelemetry Observability Source: https://www.jobrunr.io/en/documentation/pro/observability Enable OpenTelemetry-based observability for JobRunr Pro. This facilitates distributed tracing and allows for detailed job information to be viewed in your observability platform. ```properties # or, if you prefer OpenTelemetry jobrunr.jobs.metrics.otel-observability.enabled=true ``` -------------------------------- ### Sending Emails to All Subscribers (Batch Method) Source: https://www.jobrunr.io/en/documentation/pro/batches This code showcases the recommended JobRunr Pro batch method for sending emails. It uses `BackgroundJob.startBatch` to ensure atomicity. Child jobs are enqueued in a separate method to allow JobRunr to analyze the batch correctly. ```java public class NewsletterService { @Inject private UserRepository userRepository; public void sendEmailsToAllSubscribers() { BackgroundJob.startBatch(this::sendEmailToEachSubscriber); } public void sendEmailToEachSubscriber() { List users = userRepository.getAllUsers(); for(User user : users) { BackgroundJob.enqueue(() -> mailService.send(user.getId(), "mail-template-key")); } } } ``` -------------------------------- ### Enable Micrometer Job Metrics Source: https://www.jobrunr.io/en/documentation/pro/observability Configure JobRunr Pro to export general job metrics and specific job timing metrics using Micrometer. This allows integration with tools like Prometheus and Grafana. ```properties # enable general jobs metrics and integrate with your framework jobrunr.jobs.metrics.enabled=true # enable job timing metrics (Pro only) jobrunr.jobs.metrics.micrometer-timers.enabled=true ``` -------------------------------- ### Configure Priority Queues with Fluent API Source: https://www.jobrunr.io/en/documentation/pro/priority-queues Configure priority queues using the fluent API by specifying all queue names as strings. The order matters: default queue first, then highest to lowest priority. ```java JobRunrPro .configure() .usePriorityQueues(DefaultQueue, HighPrioQueue, DefaultQueue, LowPrioQueue) ... ``` -------------------------------- ### Configure JobRunr with DefaultSqlStorageProvider Source: https://www.jobrunr.io/en/documentation/installation/storage Configure JobRunr to use a DefaultSqlStorageProvider, skipping automatic table creation. This is typically used when tables are managed manually. ```java JobRunr.configure() .useStorageProvider(new DefaultSqlStorageProvider(dataSource, DatabaseOptions.SKIP_CREATE)) .useBackgroundJobServer() .initialize(); ``` -------------------------------- ### Configure Sliding Time Window Rate Limiter with Spring Boot/Quarkus/Micronaut Source: https://www.jobrunr.io/en/documentation/pro/rate-limiters Configure a sliding time window rate limiter using application properties. This sets a limit of 2 executions every 5 seconds for jobs tagged with 'my-rate-limiter'. ```properties jobrunr.jobs.rate-limiter.sliding-time-window-rate-limiter.my-rate-limiter=2/PT5S ``` -------------------------------- ### Returning Jobs from Java 8 Lambdas Source: https://www.jobrunr.io/en/documentation/pro/results Demonstrates how to return a result from a job defined using a Java 8 lambda. Simply return the computed value from the lambda expression. ```java WeatherPrediction predictWeather(UUID cityId) { // take input and do some heavy calculations // then, just return the result return new WeatherPredication(result); } ``` -------------------------------- ### Gradle Configuration for Kotlin Serialization Source: https://www.jobrunr.io/en/documentation/serialization/kotlinx-serialization Add Kotlin Serialization and JobRunr's Kotlin support to your Gradle project. Ensure you specify the plugin version and use the latest dependency versions. ```gradle plugins { kotlin("plugin.serialization") version // ... specify your version } dependencies { // versions are omitted, use the latest versions implementation("org.jobrunr:jobrunr-kotlin-support") implementation("org.jetbrains.kotlinx:kotlinx-serialization-json") } ``` -------------------------------- ### Run Job on the Server That Created It Source: https://www.jobrunr.io/en/documentation/pro/server-tags Use the special server tag `%CURRENT_SERVER` to ensure a job runs on the same server where it was enqueued or scheduled. This is useful for jobs that depend on local resources. ```java @Job(runOnServerWithTag = "%CURRENT_SERVER") public void doWorkOnCurrentServers() { System.out.println("This will only run on the same server as where the job was enqueued or scheduled."); } ``` -------------------------------- ### Configure Multicast Address via Fluent API Source: https://www.jobrunr.io/en/documentation/pro/instant-job-processing Configure the multicast address using the Fluent API in JobRunr Pro for instant job processing. Ensure this is done before configuring the dashboard and background job server. ```java JobRunrPro .configure() // ... your usual config .useMultiCastAddress(new URI("udp://239.076.159.181:8379")) .useDashboard(...) .useBackgroundJobServer(...) ``` -------------------------------- ### Configure GitHub Issue Tracking Integration Source: https://www.jobrunr.io/en/documentation/pro/issuetracking-integration Configure JobRunr Pro to integrate with GitHub for issue tracking. Set the organization, repository, labels, and assignees. ```properties jobrunr.dashboard.integrations.issue-tracking.github.organization=jobrunr jobrunr.dashboard.integrations.issue-tracking.github.repo=jobrunr jobrunr.dashboard.integrations.issue-tracking.github.labels=bug jobrunr.dashboard.integrations.issue-tracking.github.assignees=me-myself-and-i ``` -------------------------------- ### Configure Multicast Address via Framework Property Source: https://www.jobrunr.io/en/documentation/pro/instant-job-processing Set the multicast group address in your framework's configuration properties to enable instant job processing. ```properties jobrunr.multicast-group-address=udp://239.076.159.181:8379 ``` -------------------------------- ### Configure Round Robin Dynamic Queues with Fluent API Source: https://www.jobrunr.io/en/documentation/pro/dynamic-queues Configure round robin dynamic queues using the Fluent API by specifying a label prefix for tenant identification. This ensures equal resource distribution among dynamic queues. ```java JobRunrPro.configure() .useStorageProvider(SqlStorageProviderFactory.using(dataSource)) .useBackgroundJobServer(usingStandardBackgroundJobServerConfiguration() .andWorkerCount(100) .andDynamicQueuePolicy(new RoundRobinDynamicQueuePolicy("tenant:"))) .useDashboard(usingStandardDashboardConfiguration() .andDynamicQueueConfiguration("Tenants", "tenant:")) .initialize(); ``` -------------------------------- ### JobRunr Configuration Properties Source: https://www.jobrunr.io/en/documentation/configuration/spring This snippet lists all available configuration properties for JobRunr. These properties can be set in the application.properties file to customize JobRunr's behavior. ```properties jobrunr.database.skip-create=false jobrunr.database.table-prefix= # allows to set a table prefix (e.g. schema or schema and tableprefix for all tables. e.g. MYSCHEMA._jobrunr) jobrunr.database.database-name=jobrunr # Override the default database name to use (e.g. use main application database) jobrunr.database.datasource= # allows to specify a DataSource specifically for JobRunr jobrunr.database.type= # if you have multiple supported storage providers available in your application (e.g. an SQL DataSource and a NoSQL one), it allows to specify which database to choose. Valid values are 'sql', 'mongodb'. jobrunr.jobs.default-number-of-retries=10 #the default number of retries for a failing job jobrunr.jobs.retry-back-off-time-seed=3 #the default time seed for the exponential back-off policy. jobrunr.jobs.metrics.enabled=false #Micrometer integration - this was true in v5. jobrunr.job-scheduler.enabled=true jobrunr.background-job-server.enabled=false jobrunr.background-job-server.worker-count= #this value normally is defined by the amount of CPU's that are available jobrunr.background-job-server.poll-interval-in-seconds=15 #check for new work every 15 seconds jobrunr.background-job-server.delete-succeeded-jobs-after=36h #succeeded jobs will go to the deleted state after 36 hours jobrunr.background-job-server.permanently-delete-deleted-jobs-after=72h #deleted jobs will be deleted permanently after 72 hours jobrunr.background-job-server.metrics.enabled=true # Micrometer integration: reports server metrics (cpu usage, memory usage, worker pool size, etc.) jobrunr.dashboard.enabled=false jobrunr.dashboard.port=8000 #the port on which to start the dashboard jobrunr.dashboard.username= # The username for the basic authentication which protects the dashboard. By default, no authentication is required jobrunr.dashboard.password= # The password for the basic authentication user which protects the dashboard jobrunr.miscellaneous.allow-anonymous-data-usage=true #this sends the amount of succeeded jobs for marketing purposes ``` -------------------------------- ### Fetching Job Results Source: https://www.jobrunr.io/en/documentation/pro/results This snippet shows how to fetch the result of a job using its ID. It also demonstrates how to handle cases where the result is not yet available, by throwing a `BackOffException` with an estimated availability time. ```java void startWeatherPrediction(UUID cityId) { Observation observation = observationService.getLatestObservation(cityId); // the original observation BackgroundJob.enqueue(myId, () -> weatherService.predictWeather(cityId, observation)); } WeatherPrediction getWeatherPrediction(UUID cityId) { JobResultWithBackOffInfo jobResult = BackgroundJob.getJobResult(jobId); if(jobResult.isAvailable()) return jobResult.getResult(); throw new BackOffException(Instant.now().plus(jobResult.backoffPeriod())); } ``` -------------------------------- ### Maven Settings for Repository Credentials Source: https://www.jobrunr.io/en/documentation/pro/installation Provide your JobRunr Pro Maven repository credentials in your Maven settings.xml file. ```xml JobRunrPro ${jobrunrProAccess.userName} ${jobrunrProAccess.password} ``` -------------------------------- ### Enable Job Metrics Source: https://www.jobrunr.io/en/documentation/configuration/metrics Set this property to true in application.properties to enable job-specific metrics. This is disabled by default to conserve resources. ```properties jobrunr.jobs.metrics.enabled=true ``` -------------------------------- ### Create a Job with JobBuilder and JobLambda Source: https://www.jobrunr.io/en/documentation/background-methods Use JobBuilder to create a job with configurable properties like name, retries, and labels, using a JobLambda for the job logic. Access JobScheduler via dependency injection or use the singleton. ```java jobScheduler.create(aJob() .withName("A job requested for " + name) .withAmountOfRetries(3) .withLabels("tenant-A", "from-rest-api") .withJobLambda(() -> sampleService.executeExampleJob(name))); ``` -------------------------------- ### Implement Re-entrant Background Methods Source: https://www.jobrunr.io/en/documentation/background-methods/best-practices Ensure background methods can be safely interrupted and retried. This prevents issues like sending duplicate emails by checking if the action has already been performed. ```java public void sendWelcomeEmail(Long userId) { User user = userRepository.getUserById(userId); emailService.Send(user.getEmailAddress(), "Hello!"); } ``` ```java public void sendWelcomeEmail(Long userId) { User user = userRepository.getUserById(userId); if (user.IsWelcomeEmailNotSent()) { emailService.Send(user.getEmailAddress(), "Hello!"); user.setWelcomeEmailSent(true); userRepository.save(user); } } ``` -------------------------------- ### Create a Job with JobBuilder and JobRequest Source: https://www.jobrunr.io/en/documentation/background-methods Use JobBuilder to create a job with configurable properties, passing a JobRequest instance to the builder. Access JobRequestScheduler via dependency injection or use the singleton. ```java jobRequestScheduler.create(aJob() .withName("A job requested for " + name) .withAmountOfRetries(3) .withLabels("tenant-A", "from-rest-api") .withJobRequest(new MyJobRequest(id))); ``` -------------------------------- ### Implement a JobRequestHandler Source: https://www.jobrunr.io/en/documentation/background-methods Create a JobRequestHandler service to process JobRequests. Services can be injected into the handler, and the run method receives the JobRequest. ```java @Component public class MyJobRequestHandler implements JobRequestHandler { @Inject private SomeService someService; // you can inject other services (or constructor-injection) @Override @Job(name = "Some neat Job Display Name", retries = 2) public void run(MyJobRequest jobRequest) { // do your background work here } } ``` -------------------------------- ### Custom License Key Provider with @Produces Source: https://www.jobrunr.io/en/documentation/pro/installation Implement a custom license key provider using the @Produces annotation, commonly used in CDI (Contexts and Dependency Injection) environments. ```java @Produces public LicenseKeyProvider licenseKeyProvider() { return new MyCustomLicenseKeyProvider(); } ``` -------------------------------- ### Schedule Job on First Day of the Month Source: https://www.jobrunr.io/en/documentation/pro/advanced-cron-expressions Schedules a job to run at a specific time on the first day of every month. Use this for monthly recurring tasks that need to execute at the beginning of the month. ```java BackgroundJob.scheduleRecurrently(Cron.firstDayOfTheMonth(10, 30), () -> System.out.println("First day of the month!")); ``` -------------------------------- ### Programmatic Configuration of ExposedTransactionAwareConnectionProvider with Fluent API Source: https://www.jobrunr.io/en/documentation/pro/transactions This snippet demonstrates how to configure an ExposedTransactionAwareConnectionProvider when using JobRunr Pro's fluent API. This is an alternative to Spring bean configuration. ```java JobRunrPro.configure() // ... .useStorageProvider(SqlStorageProviderFactory.using( dataSource, null, new ExposedTransactionAwareConnectionProvider(), new DatabaseOptions(false) )) // ... .initialize(); ``` -------------------------------- ### Configure Jira Issue Tracking Integration Source: https://www.jobrunr.io/en/documentation/pro/issuetracking-integration Configure JobRunr Pro to integrate with Jira for issue tracking. Specify the root URL, project ID, and issue type. ```properties jobrunr.dashboard.integrations.issue-tracking.jira.root-url=https://[your-jira-instance].atlassian.net/ jobrunr.dashboard.integrations.issue-tracking.jira.project-id=10001 jobrunr.dashboard.integrations.issue-tracking.jira.issue-type=10007 ``` -------------------------------- ### Maven Repository Configuration Source: https://www.jobrunr.io/en/documentation/pro/installation Configure your Maven project to use the JobRunr Pro private Maven repository. ```xml JobRunrPro https://repo.jobrunr.io/private-releases ``` -------------------------------- ### Enable Background Job Server Metrics Source: https://www.jobrunr.io/en/documentation/configuration/metrics Set this property to true in application.properties to enable metrics for the background job server. This is enabled by default for Spring and Micronaut projects. ```properties jobrunr.background-job-server.metrics.enabled=true ``` -------------------------------- ### Manual Jackson 3 Configuration in JobRunr Source: https://www.jobrunr.io/en/documentation/serialization/jackson3 Manually configure JobRunr to use Jackson 3's JsonMapper if auto-detection fails. ```java JobRunr.configure() .useJsonMapper(new Jackson3JsonMapper()) //... .initialize(); ```