线程实现连续启动停,并在某一时间段内运行
Posted cnndevelop
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程实现连续启动停,并在某一时间段内运行相关的知识,希望对你有一定的参考价值。
Thread类实现
import org.springframework.stereotype.Component; @Component public class AlarmMockThread extends Thread { private volatile long startTime = System.currentTimeMillis(); private volatile long endTime = System.currentTimeMillis(); public void setTime(long startTime, long endTime) { this.startTime = startTime; this.endTime = endTime; } public void setTime(long endTime) { this.endTime = endTime; } @Override public void run() { try { while (!interrupted()) { long sysTime = System.currentTimeMillis(); if (sysTime < endTime && sysTime > startTime) { System.out.println("系统当前时间为:" + sysTime); Thread.sleep(1000); } } } catch (Exception e) { System.out.println("服务运行出现异常:" + e); } } }
控制层实现
import com.vivo.agent.alarm.common.bean.base.AlarmMockBean; import com.vivo.agent.alarm.service.base.AlarmMockThread; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.text.SimpleDateFormat; @Slf4j @RestController @RequestMapping("/alarm") public class AlarmMockController { private AlarmMockThread thread = new AlarmMockThread(); @RequestMapping( method = RequestMethod.POST, value = "/startAlarmMock", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8", headers = "Accept=application/json") public void startAlarmMock(@RequestBody AlarmMockBean alarmMockBean) { log.info("请求到了Controller层"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); try { long startTime = format.parse(alarmMockBean.getStartTime()).getTime(); long endTime = format.parse(alarmMockBean.getEndTime()).getTime(); thread.setTime(startTime, endTime); thread.start(); } catch (Exception e) { if (e instanceof IllegalThreadStateException) { thread.run(); } } } @GetMapping("/stopAlarm") @ResponseStatus(HttpStatus.OK) public void stopAlarm() { log.info("停止报警推送接口"); thread.interrupt(); thread.setTime(System.currentTimeMillis() - 1); log.info("需要停止的线程id为:{}", thread.getId()); } }
请求的消息体格式
{ "startTime":"2020-04-06 18:58:00", "endTime":"2020-04-06 19:58:00", "dominName":"1", "ServiceName":"1", "stuteCode":{ "200":"80", "404":"20" } }
以上是关于线程实现连续启动停,并在某一时间段内运行的主要内容,如果未能解决你的问题,请参考以下文章
lucene-查询query->RangeQuery在某一范围内搜索