利用Linux中的crontab實現分佈式項目定時任務

@Controller
@RequestMapping("/task/topic")
public class TopicQuartzController {
	protected Logger logger = LoggerFactory.getLogger(TopicQuartzController.class);
	@Autowired
	private LiveTopicService liveTopicService;

	@RequestMapping("execute")
	@ResponseBody
	public CommonResult execute(HttpServletRequest request,HttpServletResponse response,String type){
		long t1 = System.currentTimeMillis();
		logger.error("topic定時器執行開始"+type);
		CommonResult result = new CommonResult();
		if(QlchatUtil.isEmpty(type)){
			result.setMsg("參數爲空");
			result.setSuccess(false);
			return result;
		}
		try {
			switch (type) {
				case "autoEndTopic":
					this.autoEndTopic();
					break;
				case "oneWeek":
					this.endTopicOneWeek();
					break;
				default:
					break;
			}
			result.setSuccess(true);
			result.setMsg("執行完成" + type);
		} catch (Exception e) {
			logger.error("topic定時器執行異常" + type, e);
			result.setMsg("topic定時器執行異常" + type);
			result.setSuccess(false);
		}
		long t2 = System.currentTimeMillis();
		logger.error("topic定時器執行結束"+type+",耗時="+(t2 - t1) + "ms");
		return result;
	}

	private void autoEndTopic(){
		String sql = "SELECT id_ topicId FROM skg_live_topic lt WHERE lt.`status_` = 'beginning' AND lt.end_time_ IS NOT NULL AND lt.`end_time_` < NOW()";
		JdbcTemplate jdbcTemplate = SpringHelper.getBean(JdbcTemplate.class);
		List<Map<String, Object>> resultMap = jdbcTemplate.queryForList(sql);
		for (Map<String, Object> map : resultMap) {
			String topicId = String.valueOf(map.get("topicId"));
			try {
				LiveTopicPo liveTopicPo = liveTopicService.loadCache(topicId);
				liveTopicService.endTopic(liveTopicPo, liveTopicPo.getCreateBy());
			}catch (Exception e){
				logger.error("autoEndTopic異常" + topicId, e);
			}
		}
	}

	/**
	 * 結束之前的沒有結束時間的話題,只跑一週
	 */
	private void endTopicOneWeek(){
		String sql = "SELECT id_ topicId FROM skg_live_topic lt WHERE lt.`status_` = 'beginning' AND lt.end_time_ IS NULL AND lt.start_time_ <= (NOW() - interval 48 hour)";
		JdbcTemplate jdbcTemplate = SpringHelper.getBean(JdbcTemplate.class);
		List<Map<String, Object>> resultMap = jdbcTemplate.queryForList(sql);
		for (Map<String, Object> map : resultMap) {
			String topicId = String.valueOf(map.get("topicId"));
			try {
				LiveTopicPo liveTopicPo = liveTopicService.loadCache(topicId);
				liveTopicService.endTopic(liveTopicPo, liveTopicPo.getCreateBy());
			}catch (Exception e){
				logger.error("autoEndTopic異常" + topicId, e);
			}
		}
	}
}

像上面這樣寫好定時任務的邏輯類

創建一個contab.txt

*/30 * * * * curl 'http://10.47.161.40:8181/task/topic/execute.do?type=oneWeek'
*/30 * * * * curl 'http://10.47.161.40:8181/task/topic/execute.do?type=autoEndTopic'
裏面這樣調用方法去執行即可實現分佈式項目的定時任務

上面即每30分鐘執行一次

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章