条件触发定时任务的开始和停止
业务需求:答题游戏开始后,每m秒统计一次结果。答题答完n次后,停止定时任务。
第一步:springBoot启动类的设置
@SpringBootApplication
@EnableScheduling
public class App {
public static ConcurrentHashMap< String, ScheduledFuture> map = new ConcurrentHashMap < String, ScheduledFuture> ( ) ;
public static void main ( String[ ] args) {
SpringApplication. run ( App. class , args) ;
}
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler ( ) {
ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler ( ) ;
executor. setPoolSize ( 20 ) ;
executor. setThreadNamePrefix ( "threadPoolTaskSchedulerExecutor-" ) ;
executor. setWaitForTasksToCompleteOnShutdown ( true ) ;
executor. setAwaitTerminationSeconds ( 60 ) ;
return executor;
}
}
第二步:主体代码
@Controller
@RequestMapping ( "/api" )
public class A {
private static Logger logger = LoggerFactory. getLogger ( A. class ) ;
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private ScheduledFuture< ? > future;
@RequestMapping ( "/startTask" )
public void method ( String teamId) {
Date date = new Date ( ) ;
logger. info ( "开始进入的时间为 [{}]" , date. toLocaleString ( ) ) ;
Calendar instance = Calendar. getInstance ( ) ;
instance. setTime ( date) ;
instance. add ( Calendar. SECOND, 2 ) ;
Date time = instance. getTime ( ) ;
logger. info ( "定时任务开始时间为 [{}]" , time. toLocaleString ( ) ) ;
ScheduledFuture< ? > schedule1 = threadPoolTaskScheduler. scheduleWithFixedDelay ( new DemoTask ( teamId) , time, 5000 ) ;
App. map. put ( teamId, schedule1) ;
}
public void stopTask ( String teamId) {
logger. info ( "真的调用了停止定时任务的方法!" ) ;
ScheduledFuture future = App. map. get ( teamId) ;
if ( future != null) {
future. cancel ( true ) ;
}
logger. info ( "end!" ) ;
}
class DemoTask implements Runnable {
private String teamId;
private int count = 1 ;
public int getCount ( ) {
return count;
}
public void setCount ( int count) {
this . count = count;
}
public DemoTask ( String teamId) {
this . teamId = teamId;
}
public String getTeamId ( ) {
return teamId;
}
public void setTeamId ( String teamId) {
this . teamId = teamId;
}
@Override
public void run ( ) {
logger. info ( "进入定时任务的主体!" ) ;
int count1 = this . getCount ( ) ;
count1 = count1 + 1 ;
logger. info ( "增加后的次数为:" + count1) ;
this . setCount ( count1) ;
if ( count1 > 5 ) {
logger. info ( "开始调用暂停定时任务的方法!" + teamId) ;
stopTask ( teamId) ;
}
}
}
}