huliguo
16 小时以前 a432ff3c95923f9929236de9f7a9224e8517bb70
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.ruoyi.other.util;
 
import lombok.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalTime;
import java.util.Random;
 
@Service
public class EnergyRefreshService {
    private final Random random = new Random();
    private BigDecimal currentValue;
    
 
    private final BigDecimal targetLow = new BigDecimal("85");
 
    private final BigDecimal targetHigh = new BigDecimal("87");
    
 
    private final int maxIncrement = 10;
    
    private boolean isRunning = true; // 控制任务是否继续执行
 
    public EnergyRefreshService() {
        this.currentValue = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
    }
 
    // 定时任务方法
    @Scheduled(cron = "${0 */15 * * * ?}")//15分钟执行一次
    public synchronized void refreshValue() {
        // 检查是否已停止或达到目标范围
        if (!isRunning || isWithinTargetRange(currentValue)) {
            isRunning = false;
            return;
        }
        
        // 检查当前时间是否在允许的时间段内
        LocalTime now = LocalTime.now();
        boolean isInMorning = now.isAfter(LocalTime.of(10, 0)) && now.isBefore(LocalTime.of(12, 0));
        boolean isInAfternoon = now.isAfter(LocalTime.of(15, 0)) && now.isBefore(LocalTime.of(21, 0));
        
        if (!isInMorning && !isInAfternoon) {
            return;
        }
        
        // 生成随机增量并更新值
        int increment = random.nextInt(maxIncrement + 1);
        currentValue = currentValue.add(BigDecimal.valueOf(increment))
                                   .setScale(2, RoundingMode.HALF_UP);
        
        System.out.printf("定时刷新:当前时间 %s,当前值:%.2f%n", now, currentValue);
    }
    
    private boolean isWithinTargetRange(BigDecimal value) {
        return value.compareTo(targetLow) >= 0 && value.compareTo(targetHigh) <= 0;
    }
    
    // 提供获取当前值的方法
    public BigDecimal getCurrentValue() {
        return currentValue;
    }
    
    // 重置任务
    public void reset() {
        this.currentValue = BigDecimal.ZERO;
        this.isRunning = true;
    }
 
 
}