Producer
π Purpose
The CampaignExecutionProducer component is responsible for automatically creating CampaignExecution instances based on a preconfigured schedule. It periodically checks campaigns with status SCHEDULED and triggers execution if the time has come.
π§ Class: CampaignExecutionProducer
CampaignExecutionProducer@Component
public class CampaignExecutionProducer {
@Autowired
private CampaignRepository campaignRepository;
@Autowired
private CampaignExecutionService executionService;
@Autowired
private TransactionTemplateBuilder ttb;
@SchedulerLock(name = "CampaignExecutionProducer_produce", lockAtMostFor = "PT5M", lockAtLeastFor = "PT30S")
@Scheduled(initialDelay = 120_000, fixedDelayString = "${campaign.execution.producer.fixedDelay}")
public void produce() {
final LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
campaignRepository.findAutomaticScheduledCampaigns()
.forEach(id -> {
ttb.requiresNew().executeWithoutResult(s -> {
Campaign campaign = campaignRepository.getSync(id);
if (campaign.isActive()
&& campaign.getAutomaticCampaignStatus() == AutomaticCampaignStatus.SCHEDULED
&& isWaitNewExecution(campaign, now)) {
executionService.createExecution(campaign);
campaignRepository.saveAndFlush(campaign);
}
});
});
}
// Helper methods below...
}β° Execution Frequency
The @Scheduled annotation launches the produce() method at intervals defined in configuration:
The @SchedulerLock annotation (via Shedlock) ensures the method runs in only one service instance in a clustered deployment.
π§ Conditions for Creating a New CampaignExecution
The produce() method creates a new execution only if all of the following are true:
The campaign is active
Its status is SCHEDULED
The current time
nowis equal to or afterdateTimeExecutionDepending on the
restartableflag, one of the following applies:All previous executions are
DISABLEDThe next scheduled interval has arrived (based on restart configuration)
π Support for restartable Campaigns
restartable Campaignsβ
If restartable = false
Only one execution is allowed β further executions require all previous ones to be disabled.
π If restartable = true
This enables cyclic execution (e.g., once every hour/day) based on restartableUnit and restartableUnitType.
π§© Helper Method
This method consolidates all logic for determining whether a new execution should be created.
π Example Behavior
Campaign A:
executionType = AUTOMATICdateTimeExecution = 2025-05-01T09:00restartable = truerestartableUnitType = HOURS,restartableUnit = 6
Producer output:
May 1, 09:00 β first execution
May 1, 15:00 β second execution
May 1, 21:00 β third execution
...
π Summary
CampaignExecutionProduceris an automatic campaign schedulerControlled via
@Scheduledand@SchedulerLockChecks campaign status, activation, execution time, and recurrence settings
Operates in a new isolated transaction, preventing interference with outer processes
Last updated
Was this helpful?