Skip to content

Instantly share code, notes, and snippets.

@steklopod
Created August 2, 2020 13:11
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save steklopod/0ec1d2b3df114fc0857e1c6afd0d61eb to your computer and use it in GitHub Desktop.
Spring boot cron
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
@NoArgsConstructor
@Getter
@Setter
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class CronScheduledConfig {
@NotNull
@Pattern(regexp = "^.+\\s.+\\s.+\\s.+\\s.+\\s.+$")
private String cronScheduler;
private Boolean enabled;
@NotNull
@Min(message = "Parameter 'amount' can not be less than 1", value = 1)
private Long amount;
@NotEmpty(message = "Parameter 'unit' can not be empty")
private ChronoUnit unit;
}
/* biometry-obsolescence:
enabled: false
cron-scheduler: 0 0 3 * * * # Everyday at 3AM
unit: years
amount: 3
*/
@Slf4j
@Service
@AllArgsConstructor
public class SchedulerStarter {
public static final String START_SCHEDULING_MESSAGE = "Start scheduling with config {}";
private final SessionDeactivation sessionDeactivation;
private final OriginalsCleaner originalsCleaner;
private final BiometricsDeactivation biometricsDeactivation;
private final PeriodicScheduledConfig sessionProperties;
private final CronScheduledConfig biometricProperties;
private final CronScheduledConfig originalProperties;
@Scheduled(fixedDelayString = "#{sessionDeactivationConfig.getPeriodicity()}")
public void callSessionDeactivation() {
if (sessionProperties.getEnabled() == null || sessionProperties.getEnabled()) {
log.info("Start scheduled user session auto-closing mechanism");
log.debug(START_SCHEDULING_MESSAGE, sessionProperties);
Duration liveDuration = Duration.of(sessionProperties.getAmount(), sessionProperties.getUnit());
LocalDateTime updatedBefore = now().minusMinutes(liveDuration.toMinutes());
sessionDeactivation.autoClose(updatedBefore);
} else {
log.info("User session auto-closing mechanism is disable");
}
}
public Long getPeriodicity() {
return ChronoUnit.MINUTES.getDuration().toMillis();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment