Java tutorial
/******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.showcase.demos.schedule; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.apache.commons.lang3.Validate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.support.TaskUtils; import org.springside.modules.utils.Threads; import com.google.common.util.concurrent.ThreadFactoryBuilder; /** * JDKScheduledThreadPoolExecutor * SpringTask NameSpace?, ????. * * @author calvin */ public class JdkTimerJob implements Runnable { private int initialDelay = 0; private int period = 0; private int shutdownTimeout = Integer.MAX_VALUE; private ScheduledExecutorService scheduledExecutorService; @Autowired private UserCountScanner userCountScanner; @PostConstruct public void start() throws Exception { Validate.isTrue(period > 0); // ?schedule, Spring TaskUtilsLOG_AND_SUPPRESS_ERROR_HANDLER? Runnable task = TaskUtils.decorateTaskWithErrorHandler(this, null, true); // ?SechdulerExecutor,guavaThreadFactoryBuilder??? scheduledExecutorService = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder().setNameFormat("JdkTimerJob-%1$d").build()); // scheduleAtFixedRatefixRate() ?. // scheduleAtFixedDelay() ???. scheduledExecutorService.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS); } @PreDestroy public void stop() { Threads.normalShutdown(scheduledExecutorService, shutdownTimeout, TimeUnit.SECONDS); } /** * ??. */ @Override public void run() { userCountScanner.executeByJdk(); } /** * ??. */ public void setInitialDelay(int initialDelay) { this.initialDelay = initialDelay; } /** * ,??. */ public void setPeriod(int period) { this.period = period; } /** * normalShutdown, ??. */ public void setShutdownTimeout(int shutdownTimeout) { this.shutdownTimeout = shutdownTimeout; } }