Skip to content

Annotations Reference

Declarative configuration for Ratchet jobs. These annotations provide a zero-code-configuration approach to scheduling, resilience, and retry behavior.

@Recurring

Marks a method for cron-scheduled recurring execution. Annotated methods are automatically discovered at application startup and registered with the job scheduler.

Package: run.ratchet.apiTarget: Method Retention: Runtime

java
@Recurring(
    cron = "0 0 2 * * ?",
    zone = "America/New_York",
    id = "nightly-cleanup",
    name = "Nightly Cleanup",
    enabled = true,
    priority = 5,
    maxRetries = 3,
    backoffPolicy = BackoffPolicy.EXPONENTIAL,
    backoffDelayMs = 1000,
    misfirePolicy = RecurringMisfirePolicy.Action.CATCH_UP,
    maxCatchUpExecutions = 11,
    timeoutSeconds = 3600,
    tags = {"maintenance", "nightly"}
)

Attributes

AttributeTypeDefaultRequiredDescription
cronString--YesQuartz cron expression (6-7 fields)
zoneString"UTC"NoTimezone for cron evaluation. Must be a valid ZoneId.
idString""NoStable recurring-job business key. If empty, defaults to fully qualified class + method name. After trimming, it must contain at most 255 printable ASCII characters. This is not the persisted UUIDv7 job ID.
nameString""NoHuman-readable name for logs and monitoring. Defaults to method name.
enabledbooleantrueNoWhether the job is registered at startup.
priorityint5NoPriority on a 1-10 scale. Mapped to JobPriority (see mapping).
maxRetriesint3NoMaximum retry attempts on failure.
backoffPolicyBackoffPolicyEXPONENTIALNoRetry delay strategy: NONE, FIXED, or EXPONENTIAL.
backoffDelayMslong1000NoBase delay in milliseconds for backoff calculations.
misfirePolicyRecurringMisfirePolicy.ActionCATCH_UPNoBacklog action: SKIP, FIRE_ONCE, or bounded CATCH_UP. A backlog means at least two cron occurrences are overdue.
maxCatchUpExecutionsint11NoMaximum total overdue occurrences created by CATCH_UP. It is ignored and has no effect for SKIP or FIRE_ONCE.
timeoutSecondslong3600NoMaximum execution time in seconds (default: 1 hour).
tagsString[]{}NoTags for filtering and categorization.

Cron expression format

Uses Quartz cron format with 6-7 fields:

second minute hour day-of-month month day-of-week [year]
ExpressionSchedule
0 0 2 * * ?Every day at 2:00 AM
0 */15 * * * ?Every 15 minutes
0 0 9 ? * MONEvery Monday at 9:00 AM
0 0 0 1 * ?First day of every month at midnight
0 30 8 ? * MON-FRIWeekdays at 8:30 AM

Method requirements

  • Must be public
  • Must have no parameters or a single JobContext parameter
  • Must be in a CDI-managed bean (e.g., @ApplicationScoped)
  • Return type is ignored

Examples

java
@ApplicationScoped
public class MaintenanceService {

    // Simple recurring job -- runs at 2 AM daily
    @Recurring(cron = "0 0 2 * * ?", name = "Nightly Cleanup")
    public void performCleanup() {
        // cleanup logic
    }

    // With JobContext for logging and parameters
    @Recurring(
        cron = "0 */30 * * * ?",
        zone = "America/New_York",
        name = "Data Sync"
    )
    public void syncData(JobContext ctx) {
        ctx.logger().info("Starting sync for job " + ctx.jobId());
        // sync logic
    }

    // High-priority with custom retry policy
    @Recurring(
        cron = "0 0 * * * ?",
        name = "Hourly Health Check",
        priority = 9,
        maxRetries = 5,
        backoffPolicy = BackoffPolicy.EXPONENTIAL,
        backoffDelayMs = 2000,
        tags = {"health", "monitoring"}
    )
    public void healthCheck() {
        // health check logic
    }

    // Discard an outage backlog and resume at the next future cron time
    @Recurring(
        cron = "0 * * * * ?",
        misfirePolicy = RecurringMisfirePolicy.Action.SKIP
    )
    public void refreshCache() {
        // a single late occurrence still runs normally
    }

    // Explicitly disabled
    @Recurring(
        cron = "0 0 3 * * ?",
        name = "Archive Old Records",
        enabled = false
    )
    public void archiveRecords() {
        // archiving logic
    }
}

Lifecycle

  1. At application startup, Ratchet scans CDI beans for @Recurring methods.
  2. For each annotated method, a recurring job definition is registered using the id as the business key.
  3. The scheduler creates individual job instances at each scheduled execution time, applying the persisted misfire policy when at least two occurrences are overdue.
  4. If a job with the same business key is already active (PENDING/RUNNING), it is replaced.

@CircuitBreakerProtected

Wraps method invocations through the configured ResilienceStrategy for circuit breaker protection. When the circuit opens, calls fail fast with CircuitBreakerOpenException.

Package: run.ratchet.apiTarget: Type, Method Retention: Runtime Meta-annotations: @InterceptorBinding, @Inherited

INFO

This annotation is marked @Incubating and may change in future versions.

java
@CircuitBreakerProtected(
    service = "payment-gateway",
    profile = CircuitBreakerProfile.EXTERNAL_API
)

Attributes

AttributeTypeDefaultRequiredDescription
serviceString""NoService name for grouping circuit breakers; when blank, the breaker key is derived from the method name. Used in logging and monitoring.
profileCircuitBreakerProfileDEFAULTNoPre-configured circuit breaker profile.

CircuitBreakerProfile

Pre-configured profiles for common use cases:

ProfileUse CaseFailure ThresholdSliding WindowWait Duration
DEFAULTGeneral internal services50%100 calls30 seconds
FASTQuick failure detection50%20 calls10 seconds
CRITICALHigh-availability services75%200 calls60 seconds
EXTERNAL_APIThird-party integrations60%50 calls60 seconds
CLAIM_PATHPoller store-claim path50%20 calls5 seconds

Examples

java
@ApplicationScoped
public class PaymentGateway {

    // Method-level circuit breaker
    @CircuitBreakerProtected(
        service = "stripe-api",
        profile = CircuitBreakerProfile.EXTERNAL_API
    )
    public PaymentResult charge(PaymentRequest req) {
        return stripeClient.charge(req);
    }
}

// Class-level circuit breaker (applies to all methods)
@CircuitBreakerProtected(service = "inventory-service")
@ApplicationScoped
public class InventoryClient {
    public int checkStock(String sku) { /* ... */ }
    public void reserveStock(String sku, int qty) { /* ... */ }
}

When the circuit breaker opens, calls throw CircuitBreakerOpenException immediately without invoking the protected method.

@DoNotRetry

Marks an exception class as permanently non-retryable. When a job fails with an exception annotated with @DoNotRetry, the scheduler skips retry attempts and moves the job directly to the dead letter queue.

Package: run.ratchet.apiTarget: Type (applied to exception classes) Retention: Runtime

java
@DoNotRetry("Validation errors should not be retried")
public class ValidationException extends Exception {
    // Exception marked as non-retryable
}

Attributes

AttributeTypeDefaultDescription
valueString""Optional human-readable reason why retries should be skipped

Example

java
// Define a non-retryable exception
@DoNotRetry("Business validation failures are permanent")
public class ValidationException extends RuntimeException {
    public ValidationException(String message) {
        super(message);
    }
}

// When this exception is thrown, the job goes straight to DLQ
@ApplicationScoped
public class OrderProcessor {
    public void processOrder(long orderId) {
        Order order = orderRepository.find(orderId);
        if (order.total().compareTo(BigDecimal.ZERO) < 0) {
            throw new ValidationException("Order total cannot be negative");
        }
        // process...
    }
}

Use @DoNotRetry for exceptions that represent permanent failures:

  • Business rule violations
  • Data validation errors
  • Authorization failures
  • Malformed input

Do not use it for transient failures that might succeed on retry (network timeouts, database lock contention, etc.).

@Incubating

Marks APIs that are experimental and may change in future versions without following the normal deprecation cycle.

Package: run.ratchet.apiTarget: Type, Method, Field, Package Retention: Runtime

java
@Incubating
public interface ResilienceStrategy {
    // This SPI may change in a future version
}

@Incubating is applied to SPI interfaces and classes that are subject to change. If you implement an @Incubating interface, be aware that method signatures may be added, changed, or removed in minor releases.

Currently @Incubating SPIs include the scheduler extension contracts in run.ratchet.spi, including RatchetConfigSource, JobInvocationResolver, ResultPersistenceStrategy, ExecutionTuningProvider, PollingStrategyProvider, JobLoggerFactory, ResilienceStrategy, ClassPolicy, ErrorSanitizer, ExecutorProvider, BeanResolver, MetricsCollector, JobLogger, ClusterCoordinator, StartupCoordinator, and NodeIdentityProvider.

See also