当前位置: 首页 > news >正文

昆明云南微网站制作wordpress文章推荐插件

昆明云南微网站制作,wordpress文章推荐插件,wordpress 文章页调用,杭州发布最新消息文章目录 Spring Boot 定时任务从原理到实现详解一、核心原理分析1. 架构分层2. 核心组件3. 线程模型 二、基础实现步骤1. 添加依赖2. 主类配置3. 定时任务类 三、高级配置技巧1. 自定义线程池2. 动态配置参数3. 分布式锁集成#xff08;Redis示例#xff09; 四、异常处理机… 文章目录 Spring Boot 定时任务从原理到实现详解一、核心原理分析1. 架构分层2. 核心组件3. 线程模型 二、基础实现步骤1. 添加依赖2. 主类配置3. 定时任务类 三、高级配置技巧1. 自定义线程池2. 动态配置参数3. 分布式锁集成Redis示例 四、异常处理机制1. 统一异常处理器2. 任务重试机制 五、监控与调试1. Actuator 端点2. 性能监控 六、完整示例项目结构七、最佳实践建议Schedule注解参数详细说明一、注解基础参数详解1. 核心参数配置2. 参数对照表 二、Cron表达式详解1. 标准格式2. 特殊字符说明3. 常用表达式示例 三、多模式配置示例1. 基础模式组合2. 动态参数注入 四、高级使用技巧1. 多任务并行执行2. 条件化调度3. 分布式锁集成 五、异常处理机制1. 自定义异常处理器2. 重试机制 六、常见问题解决方案1. 任务不执行排查2. 多实例重复执行 七、最佳实践建议 Spring Boot 定时任务从原理到实现详解 一、核心原理分析 1. 架构分层 graph TDA[Application] -- B[EnableScheduling]B -- C[ScheduledAnnotationBeanPostProcessor]C -- D[TaskScheduler]D -- E[ThreadPoolTaskScheduler]D -- F[ConcurrentTaskScheduler]2. 核心组件 EnableScheduling启用定时任务自动配置ScheduledAnnotationBeanPostProcessor解析Scheduled注解TaskScheduler任务调度接口CronTrigger处理cron表达式 3. 线程模型 // 默认线程池配置 public class ThreadPoolTaskScheduler extends ExecutorConfigurationSupportimplements TaskScheduler, SchedulingTaskExecutor {private volatile int poolSize 1; // 默认单线程private ThreadFactory threadFactory new CustomizableThreadFactory(task-scheduler-); }二、基础实现步骤 1. 添加依赖 !-- pom.xml -- dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter/artifactId /dependency2. 主类配置 SpringBootApplication EnableScheduling public class SchedulingApplication {public static void main(String[] args) {SpringApplication.run(SchedulingApplication.class, args);} }3. 定时任务类 Component public class ScheduledTasks {private static final Logger log LoggerFactory.getLogger(ScheduledTasks.class);// 固定频率任务开始时间间隔Scheduled(fixedRate 5000)public void fixedRateTask() {log.info(Fixed Rate Task :: Execution Time - {}, LocalDateTime.now());}// 固定延迟任务结束时间间隔Scheduled(fixedDelay 7000, initialDelay 2000)public void fixedDelayTask() {log.info(Fixed Delay Task :: Execution Time - {}, LocalDateTime.now());}// Cron表达式Scheduled(cron 0 0/15 9-17 * * MON-FRI)public void cronTask() {log.info(Cron Task :: Execution Time - {}, LocalDateTime.now());} }三、高级配置技巧 1. 自定义线程池 Configuration public class SchedulerConfig implements SchedulingConfigurer {Overridepublic void configureTasks(ScheduledTaskRegistrar taskRegistrar) {ThreadPoolTaskScheduler taskScheduler new ThreadPoolTaskScheduler();taskScheduler.setPoolSize(5);taskScheduler.setThreadNamePrefix(custom-scheduler-);taskScheduler.initialize();taskRegistrar.setTaskScheduler(taskScheduler);} }2. 动态配置参数 application.properties schedule.rate10000 schedule.delay5000 schedule.cron0 0 8 * * *Scheduled(fixedRateString ${schedule.rate}) public void dynamicRateTask() {// ... }Scheduled(cron ${schedule.cron}) public void dynamicCronTask() {// ... }3. 分布式锁集成Redis示例 Scheduled(fixedRate 10000) public void distributedTask() {String lockKey scheduledTaskLock;String requestId UUID.randomUUID().toString();try {if (redisLockUtil.tryGetLock(lockKey, requestId, 30)) {log.info(Acquired lock, executing task...);// 业务逻辑}} finally {redisLockUtil.releaseLock(lockKey, requestId);} }四、异常处理机制 1. 统一异常处理器 ControllerAdvice public class SchedulingExceptionHandler {ExceptionHandler(TaskExecutionException.class)public void handleTaskException(TaskExecutionException ex) {log.error(Scheduled task failed: {}, ex.getMessage());// 发送告警通知} }2. 任务重试机制 Retryable(maxAttempts 3, backoff Backoff(delay 1000)) Scheduled(fixedRate 5000) public void retryableTask() {// 可能失败的业务逻辑if (Math.random() 0.5) {throw new RuntimeException(Simulated error);} }五、监控与调试 1. Actuator 端点 management.endpoints.web.exposure.includescheduledtasks访问 /actuator/scheduledtasks 查看任务列表 {cron: [{runnable: {target: com.example.ScheduledTasks.cronTask},expression: 0 0/15 9-17 * * MON-FRI}] }2. 性能监控 Scheduled(fixedRate 5000) Timed(value scheduled.task, description 监控任务执行时间) public void monitoredTask() {// 业务逻辑 }六、完整示例项目结构 scheduling-demo/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/example/ │ │ │ ├── config/ │ │ │ │ └── SchedulerConfig.java │ │ │ ├── ScheduledTasks.java │ │ │ └── SchedulingApplication.java │ │ └── resources/ │ │ ├── application.properties │ │ └── logback-spring.xml │ └── test/ └── pom.xml七、最佳实践建议 线程池配置原则 # 推荐线程数 CPU核心数 * 2IO密集型 # 推荐线程数 CPU核心数 1计算密集型任务设计规范 单任务执行时间 调度间隔时间添加事务边界控制避免任务间状态共享 生产环境注意事项 // 添加健康检查 Component public class ScheduleHealthIndicator implements HealthIndicator {Overridepublic Health health() {// 检查任务最后执行时间return Health.up().build();} }通过以上配置和实现可以构建出高可靠、易维护的定时任务系统。定时任务的执行频率需要根据实际业务需求进行合理设置同时要特别注意在分布式环境下的任务协调问题。 Schedule注解参数详细说明 一、注解基础参数详解 1. 核心参数配置 Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) Retention(RetentionPolicy.RUNTIME) Documented Repeatable(Schedules.class) public interface Scheduled {String cron() default ;String zone() default ;long fixedDelay() default -1;String fixedDelayString() default ;long fixedRate() default -1;String fixedRateString() default ;long initialDelay() default -1;String initialDelayString() default ; }2. 参数对照表 参数名称类型必填默认值说明cronString否“”Unix风格的cron表达式zoneString否“”时区ID如Asia/ShanghaifixedDelaylong否-1上次执行结束到下次执行的间隔毫秒fixedDelayStringString否“”支持占位符的字符串形式如${schedule.delay}fixedRatelong否-1固定频率执行毫秒fixedRateStringString否“”支持占位符的字符串形式initialDelaylong否-1首次执行的延迟时间毫秒initialDelayStringString否“”支持占位符的字符串形式 二、Cron表达式详解 1. 标准格式 秒0-59 分0-59 时0-23 日1-31 月1-12 周0-7 年可选2. 特殊字符说明 字符含义示例说明*任意值0 * * * * *每分钟0秒执行?不指定仅日/周字段0 0 0 ? * MON每周一0点执行-范围0 0 9-17 * * *每天9点到17点整点执行,多个值0 0 8,12,18 * * *每天8、12、18点执行/间隔频率0 0/15 * * * *每15分钟执行一次L最后一天/最后一周0 0 0 L * ?每月最后一天0点执行W最近工作日0 0 0 LW * ?每月最后一个工作日执行#第几个周几0 0 0 ? * 5#2每月第2个周四执行 3. 常用表达式示例 Scheduled(cron 0 0 3 * * ?) // 每天凌晨3点执行 Scheduled(cron 0 0/5 9-17 * * MON-FRI) // 工作日9-17点每5分钟执行 Scheduled(cron 0 0 12 1 * ?) // 每月1号中午12点执行 Scheduled(cron 0 0 8 L * ?) // 每月最后一天上午8点执行三、多模式配置示例 1. 基础模式组合 // 初始延迟3秒之后每5秒执行 Scheduled(initialDelay 3000, fixedRate 5000) // 每天8:30执行使用属性配置 Scheduled(cron ${app.schedule.daily-report}) 2. 动态参数注入 application.properties schedule.interval5000 schedule.initial.delay10000 schedule.cron.expression0 0/15 * * * *Scheduled(fixedRateString ${schedule.interval},initialDelayString ${schedule.initial.delay} ) public void dynamicScheduleTask() {// 业务逻辑 }Scheduled(cron ${schedule.cron.expression}) public void cronTask() {// 定时任务 }四、高级使用技巧 1. 多任务并行执行 Configuration EnableScheduling public class ScheduleConfig implements SchedulingConfigurer {Overridepublic void configureTasks(ScheduledTaskRegistrar taskRegistrar) {ThreadPoolTaskScheduler scheduler new ThreadPoolTaskScheduler();scheduler.setPoolSize(5);scheduler.setThreadNamePrefix(schedule-pool-);scheduler.initialize();taskRegistrar.setTaskScheduler(scheduler);} }2. 条件化调度 Profile(production) // 仅生产环境生效 ConditionalOnProperty(name scheduler.enabled, havingValue true) Scheduled(fixedRate 10000) public void conditionalTask() {// 生产环境专用任务 }3. 分布式锁集成 Scheduled(cron 0 0/30 * * * ?) public void distributedTask() {String lockKey reportGenerationLock;try {if (redisLock.tryLock(lockKey, 300)) { // 获取30秒锁generateReport();}} finally {redisLock.release(lockKey);} }五、异常处理机制 1. 自定义异常处理器 ControllerAdvice public class ScheduleExceptionHandler {ExceptionHandler(ScheduleExecutionException.class)public void handleScheduleException(ScheduleExecutionException ex) {log.error(定时任务执行失败: {}, ex.getMessage());// 发送告警通知alertService.sendAlert(Schedule Failure, ex.getMessage());} }2. 重试机制 Retryable(value {DataAccessException.class},maxAttempts 3,backoff Backoff(delay 1000, multiplier 2) ) Scheduled(fixedDelay 5000) public void retryableTask() {// 可能失败的数据操作databaseService.batchUpdate(); }六、常见问题解决方案 1. 任务不执行排查 1. 检查主类是否添加EnableScheduling 2. 确认任务方法为public修饰 3. 验证cron表达式有效性可用在线验证工具 4. 检查线程池是否被占满默认单线程2. 多实例重复执行 // 使用数据库锁方案示例 Transactional Scheduled(cron 0 0 3 * * ?) public void exclusiveTask() {LocalDateTime now LocalDateTime.now();ScheduleLock lock lockRepo.findByTaskName(dailyCleanup);if (lock null || lock.getLockUntil().isBefore(now)) {// 获取锁设置30分钟有效期lockRepo.save(new ScheduleLock(dailyCleanup, now.plusMinutes(30)));// 执行任务dataCleanupService.cleanup();// 释放锁lockRepo.deleteById(dailyCleanup);} }七、最佳实践建议 线程池配置原则 # 推荐配置公式 IO密集型任务线程数 CPU核心数 * 2 计算密集型任务线程数 CPU核心数 1执行时间监控 Scheduled(fixedRate 60000) public void monitoredTask() {StopWatch watch new StopWatch();try {watch.start();// 业务逻辑} finally {watch.stop();if (watch.getTotalTimeMillis() 5000) {log.warn(任务执行超时: {}ms, watch.getTotalTimeMillis());}} }重要任务日志规范 Scheduled(cron 0 0 2 * * ?) public void criticalTask() {log.info( 开始执行数据归档任务 );try {archiveService.archiveData();log.info(数据归档成功归档数量: {}, count);} catch (Exception e) {log.error(数据归档失败, e);throw e;} finally {log.info( 结束数据归档任务 );} }通过合理配置和遵循最佳实践可以构建出高可靠、易维护的定时任务系统。特别注意在分布式环境下做好任务协调避免重复执行导致的数据不一致问题。
http://www.pierceye.com/news/28655/

相关文章:

  • 怎么做免费视频网站吗有没有做定制衣服的网站
  • 湖南鸿泰电力建设有限公司网站直播软件视频软件
  • 做网站前端需要懂得公司主页格式
  • 东莞个人网站设计aspnet网站开发实战
  • 常用网站开发语言网站建设公司 资讯
  • 怎么在网站注册账号旅游网站建设设计公司
  • 浙江短视频seo优化网站网站建设十年杜绝模板
  • dw网站引导页怎么做慈溪网站建设报价
  • 优秀企业门户网站建设一级a做爰视频安全网站
  • 网站开发报价标准域名备案的网站建设方案书模板
  • 潍坊快速网站排名房地产公司网站制作
  • 怎么做网站的外部连接中国外协加工订单网
  • 抚州网站建设网络公司是干什么工作的
  • 永安网站制作管理咨询包括哪些内容
  • phpcms网站音乐代码存放在什么位置贵阳企业网站设计制作
  • 如何制作网站地图工会 网站 建设
  • 搜索引擎网站推广法 怎么做深圳专业seo外包
  • 您的网站未备案 或者原备案号被取消做网站优化找谁
  • 网站建设行杭州网站建设seo优化
  • 做行业网站德芙巧克力的软文500字
  • 做国学类网站合法吗重庆当地网站
  • 网站推广策略有哪些阿里云网站目录
  • arvixe如何做网站中国中建设计集团有限公司
  • 做网站怎样写标题做wordpress模板赚钱
  • 山西物价局建设工程检测网站首页订单展示 wordpress
  • wordpress做直播网站网络规划设计师考试资料百度云
  • 潍坊专业网站建设多少钱网页设计师做什么
  • 软文营销文章seo策略主要包括
  • 楚雄微网站建设网上政务服务平台入口
  • 怎么做乞讨网站做机电预算的网站