java里定时每个周二,周四,周六凌晨4点开始执行项目的某个类的方法具体怎么实现之前没写过关于定时,详细说明方法具体怎么写

在Java中,你可以使用ScheduledExecutorService或者Spring的@Scheduled注解来实现定时任务。下面分别展示这两种方式的示例。

使用 ScheduledExecutorService

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledTask {

    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        // 计算当前时间距离下一个周二、周四、周六凌晨4点的时间
        long initialDelay = calculateInitialDelay();

        // 每隔一周执行一次
        long period = 7 * 24 * 60 * 60 * 1000;

        // 使用 scheduleAtFixedRate 方法
        scheduler.scheduleAtFixedRate(
                ScheduledTask::runTask,
                initialDelay,
                period,
                TimeUnit.MILLISECONDS
        );
    }

    private static long calculateInitialDelay() {
        // 计算当前时间距离下一个周二、周四、周六凌晨4点的时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime nextRun = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.TUESDAY))
                .withHour(4)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);

        if (now.compareTo(nextRun) > 0) {
            nextRun = nextRun.plusWeeks(1);
        }

        return TimeUnit.MILLISECONDS.toMillis(now.until(nextRun, ChronoUnit.MILLIS));
    }

    private static void runTask() {
        // 这里放你要定时执行的任务
        System.out.println("Executing task at: " + LocalDateTime.now());
    }
}

使用 Spring 的 @Scheduled 注解

首先,确保你的项目是Spring项目。然后,创建一个Spring组件并使用@Scheduled注解

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class ScheduledTask {

    // 在每周二、周四、周六凌晨4点执行
    @Scheduled(cron = "0 0 4 ? * TUE,THU,SAT")
    public void runTask() {
        // 这里放你要定时执行的任务
        System.out.println("Executing task at: " + LocalDateTime.now());
    }
}

在这两个例子中,runTask方法中的代码将在每周二、周四、周六的凌晨4点执行。具体的执行时间可以通过Cron表达式进行配置。上述示例使用的Cron表达式是0 0 4 ? * TUE,THU,SAT,表示在每周二、周四、周六的凌晨4点执行。你可以根据自己的需求修改Cron表达式。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值