Search in sources :

Example 81 with Scheduled

use of org.springframework.scheduling.annotation.Scheduled in project weixin-boot by guhanjie.

the class AccessTokenKit method refreshToken.

@Scheduled(fixedRate = 6000000)
public synchronized void refreshToken() {
    LOGGER.info("Starting to refresh access token...");
    try {
        String url = WeixinConstants.API_ACCESS_TOKEN;
        url = url.replaceAll("APPID", weixinContants.APPID);
        url = url.replaceAll("APPSECRET", weixinContants.APPSECRET);
        WeixinHttpUtil.sendGet(url, new WeixinHttpCallback() {

            @Override
            public void process(String json) {
                AccessToken at = JSONObject.parseObject(json, AccessToken.class);
                if (at != null && at.getAccess_token() != null) {
                    token = at.getAccess_token();
                    LOGGER.info("Success to refresh access token:[{}].", token);
                } else {
                    LOGGER.error("Failed to refresh access token.");
                }
            }
        });
    } catch (Exception e) {
        LOGGER.error("Failed to refresh access token.", e);
    }
}
Also used : AccessToken(com.guhanjie.weixin.model.AccessToken) WeixinHttpCallback(com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback) Scheduled(org.springframework.scheduling.annotation.Scheduled)

Example 82 with Scheduled

use of org.springframework.scheduling.annotation.Scheduled in project Gemma by PavlidisLab.

the class SubmittedTasksMaintenance method doSubmittedTasksMaintenance.

/**
 * Check if a task has been running or queued for too long, and cancel it if necessary. Email alert will always be
 * sent in that case.
 */
@Scheduled(fixedDelay = 120000)
public void doSubmittedTasksMaintenance() {
    // Assumes collection implementing weakly consistent iterator with remove support.
    Collection<SubmittedTask<? extends TaskResult>> tasks = taskRunningService.getSubmittedTasks();
    int numQueued = 0;
    int numRunning = 0;
    int numDone = 0;
    int numCancelled = 0;
    for (SubmittedTask<?> task : tasks) {
        if (!task.getStatus().equals(SubmittedTask.Status.COMPLETED)) {
            SubmittedTasksMaintenance.log.info("Checking task: " + task.getTaskCommand().getClass().getSimpleName() + task.getTaskId() + " started=" + task.getStartTime() + " status=" + task.getStatus());
        }
        switch(task.getStatus()) {
            case QUEUED:
                numQueued++;
                Date submissionTime = task.getSubmissionTime();
                Integer maxQueueWait = task.getTaskCommand().getMaxQueueMinutes();
                assert submissionTime != null;
                assert maxQueueWait != null;
                if (submissionTime.before(DateUtils.addMinutes(new Date(), -maxQueueWait))) {
                    SubmittedTasksMaintenance.log.warn("Submitted task " + task.getTaskCommand().getClass().getSimpleName() + " has been queued for too long (max=" + maxQueueWait + "minutes), attempting to cancel: " + task.getTaskId());
                    task.addEmailAlert();
                    // -> email admin? is worker dead?
                    task.requestCancellation();
                }
                break;
            case RUNNING:
                numRunning++;
                Date startTime = task.getStartTime();
                int maxRunTime = task.getTaskCommand().getMaxRuntime();
                assert startTime != null;
                if (startTime.before(DateUtils.addMinutes(new Date(), -maxRunTime))) {
                    SubmittedTasksMaintenance.log.warn("Running task is taking too long, attempting to cancel: " + task.getTaskId() + " " + task.getTaskCommand().getClass().getSimpleName());
                    task.addEmailAlert();
                    task.requestCancellation();
                }
                break;
            case CANCELLING:
                numCancelled++;
                break;
            case FAILED:
            // fall through
            case COMPLETED:
                numDone++;
                if (task.getFinishTime().before(DateUtils.addMinutes(new Date(), -SubmittedTasksMaintenance.MAX_KEEP_TRACK_AFTER_COMPLETED_MINUTES))) {
                    SubmittedTasksMaintenance.log.debug(task.getStatus().name() + " task result not retrieved, timing out: " + task.getTaskId() + " " + task.getTaskCommand().getClass().getSimpleName());
                    // concurrent modification.
                    tasks.remove(task);
                }
                break;
            case UNKNOWN:
                break;
            default:
                break;
        }
    }
    if (tasks.size() > 0 && numDone != tasks.size())
        SubmittedTasksMaintenance.log.info(tasks.size() + " tasks monitored; Done: " + numDone + "; Running: " + numRunning + "; Cancelled: " + numCancelled + "; Queued: " + numQueued);
}
Also used : TaskResult(ubic.gemma.core.job.TaskResult) SubmittedTask(ubic.gemma.core.job.SubmittedTask) Date(java.util.Date) Scheduled(org.springframework.scheduling.annotation.Scheduled)

Example 83 with Scheduled

use of org.springframework.scheduling.annotation.Scheduled in project rpki-validator-3 by RIPE-NCC.

the class RpkiObjectCleanupService method cleanupRpkiObjects.

/**
 * Marks all RPKI objects that are reachable from a trust anchor by following the entries in the manifests.
 * Objects that are no longer reachable will be deleted after a configurable grace duration.
 */
@Scheduled(initialDelay = 60_000, fixedDelayString = "${rpki.validator.rpki.object.cleanup.interval.ms}")
public long cleanupRpkiObjects() {
    Instant now = Instant.now();
    for (TrustAnchor trustAnchor : trustAnchors.findAll()) {
        transactionTemplate.execute((status) -> {
            entityManager.setFlushMode(FlushModeType.COMMIT);
            log.debug("tracing objects for trust anchor {}", trustAnchor);
            X509ResourceCertificate resourceCertificate = trustAnchor.getCertificate();
            if (resourceCertificate != null) {
                traceCertificateAuthority(now, resourceCertificate);
            }
            return null;
        });
    }
    return deleteUnreachableObjects(now);
}
Also used : Instant(java.time.Instant) TrustAnchor(net.ripe.rpki.validator3.domain.TrustAnchor) X509ResourceCertificate(net.ripe.rpki.commons.crypto.x509cert.X509ResourceCertificate) Scheduled(org.springframework.scheduling.annotation.Scheduled)

Example 84 with Scheduled

use of org.springframework.scheduling.annotation.Scheduled in project rpki-validator-3 by RIPE-NCC.

the class ValidationRunCleanupService method cleanupValidationRuns.

@Scheduled(initialDelay = 60_000, fixedDelayString = "${rpki.validator.validation.run.cleanup.interval.ms}")
@Transactional
public long cleanupValidationRuns() {
    // Delete all validation runs older than `cleanupGraceDuration` that have a later validation run.
    Instant completedBefore = Instant.now().minus(cleanupGraceDuration);
    long removedCount = validationRuns.removeOldValidationRuns(completedBefore);
    log.info("Removed {} old validation runs", removedCount);
    return removedCount;
}
Also used : Instant(java.time.Instant) Scheduled(org.springframework.scheduling.annotation.Scheduled) Transactional(javax.transaction.Transactional)

Example 85 with Scheduled

use of org.springframework.scheduling.annotation.Scheduled in project rpki-validator-3 by RIPE-NCC.

the class RpkiRepositoryValidationService method validateRsyncRepositories.

@Scheduled(initialDelay = 10_000, fixedDelay = 10_000)
public void validateRsyncRepositories() {
    entityManager.setFlushMode(FlushModeType.COMMIT);
    Instant cutoffTime = Instant.now().minus(rsyncRepositoryDownloadInterval);
    log.info("updating all rsync repositories that have not been downloaded since {}", cutoffTime);
    Set<TrustAnchor> affectedTrustAnchors = new HashSet<>();
    final RsyncRepositoryValidationRun validationRun = new RsyncRepositoryValidationRun();
    validationRunRepository.add(validationRun);
    Stream<RpkiRepository> repositories = rpkiRepositories.findRsyncRepositories();
    Map<String, RpkiObject> objectsBySha256 = new HashMap<>();
    Map<URI, RpkiRepository> fetchedLocations = new HashMap<>();
    ValidationResult results = repositories.filter((repository) -> {
        boolean needsUpdate = repository.isPending() || repository.getLastDownloadedAt() == null || repository.getLastDownloadedAt().isBefore(cutoffTime);
        if (!needsUpdate) {
            fetchedLocations.put(URI.create(repository.getRsyncRepositoryUri()), repository);
        }
        return needsUpdate;
    }).map((repository) -> processRsyncRepository(affectedTrustAnchors, validationRun, fetchedLocations, objectsBySha256, repository)).collect(() -> ValidationResult.withLocation("placeholder"), ValidationResult::addAll, ValidationResult::addAll);
    validationRun.completeWith(results);
    affectedTrustAnchors.forEach(validationRunRepository::runCertificateTreeValidation);
}
Also used : RsyncRepositoryValidationRun(net.ripe.rpki.validator3.domain.RsyncRepositoryValidationRun) RpkiRepository(net.ripe.rpki.validator3.domain.RpkiRepository) ValidationRuns(net.ripe.rpki.validator3.domain.ValidationRuns) CertificateRepositoryObject(net.ripe.rpki.commons.crypto.CertificateRepositoryObject) RpkiRepositoryValidationRun(net.ripe.rpki.validator3.domain.RpkiRepositoryValidationRun) RsyncRepositoryValidationRun(net.ripe.rpki.validator3.domain.RsyncRepositoryValidationRun) Autowired(org.springframework.beans.factory.annotation.Autowired) ArrayUtils(org.apache.commons.lang3.ArrayUtils) FlushModeType(javax.persistence.FlushModeType) HashMap(java.util.HashMap) Scheduled(org.springframework.scheduling.annotation.Scheduled) CertificateRepositoryObjectFactory(net.ripe.rpki.commons.crypto.util.CertificateRepositoryObjectFactory) ErrorCodes(net.ripe.rpki.validator3.domain.ErrorCodes) Value(org.springframework.beans.factory.annotation.Value) HashSet(java.util.HashSet) RpkiRepositories(net.ripe.rpki.validator3.domain.RpkiRepositories) RpkiObjects(net.ripe.rpki.validator3.domain.RpkiObjects) Service(org.springframework.stereotype.Service) Locale(java.util.Locale) Duration(java.time.Duration) Map(java.util.Map) Sha256(net.ripe.rpki.validator3.util.Sha256) URI(java.net.URI) Path(java.nio.file.Path) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) TrustAnchor(net.ripe.rpki.validator3.domain.TrustAnchor) Rsync(net.ripe.rpki.commons.rsync.Rsync) Transactional(javax.transaction.Transactional) Files(java.nio.file.Files) RrdpService(net.ripe.rpki.validator3.rrdp.RrdpService) Hex(net.ripe.rpki.validator3.util.Hex) RpkiObject(net.ripe.rpki.validator3.domain.RpkiObject) Set(java.util.Set) IOException(java.io.IOException) RrdpRepositoryValidationRun(net.ripe.rpki.validator3.domain.RrdpRepositoryValidationRun) EntityManager(javax.persistence.EntityManager) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Instant(java.time.Instant) File(java.io.File) ValidationLocation(net.ripe.rpki.commons.validation.ValidationLocation) FileVisitResult(java.nio.file.FileVisitResult) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) ValidationResult(net.ripe.rpki.commons.validation.ValidationResult) RsyncUtils(net.ripe.rpki.validator3.util.RsyncUtils) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) RpkiRepository(net.ripe.rpki.validator3.domain.RpkiRepository) HashMap(java.util.HashMap) Instant(java.time.Instant) TrustAnchor(net.ripe.rpki.validator3.domain.TrustAnchor) ValidationResult(net.ripe.rpki.commons.validation.ValidationResult) URI(java.net.URI) RpkiObject(net.ripe.rpki.validator3.domain.RpkiObject) HashSet(java.util.HashSet) Scheduled(org.springframework.scheduling.annotation.Scheduled)

Aggregations

Scheduled (org.springframework.scheduling.annotation.Scheduled)140 Date (java.util.Date)38 IOException (java.io.IOException)17 HashMap (java.util.HashMap)15 ArrayList (java.util.ArrayList)12 File (java.io.File)9 List (java.util.List)9 User (io.github.jhipster.sample.domain.User)8 SimpleDateFormat (java.text.SimpleDateFormat)8 LocalDate (java.time.LocalDate)8 Map (java.util.Map)8 Word (ai.elimu.model.content.Word)6 Instant (java.time.Instant)6 SysConfig (com.itrus.portal.db.SysConfig)5 InetAddress (java.net.InetAddress)5 UnknownHostException (java.net.UnknownHostException)5 Contributor (ai.elimu.model.Contributor)4 StoryBookParagraph (ai.elimu.model.content.StoryBookParagraph)4 Language (ai.elimu.model.v2.enums.Language)4 Nabaztag (com.nabalive.data.core.model.Nabaztag)4