Sfoglia il codice sorgente

修复时区问题

JiahengHe 8 mesi fa
parent
commit
4e20c9d4dd
2 ha cambiato i file con 17 aggiunte e 15 eliminazioni
  1. 13 14
      src/core_libs.rs
  2. 4 1
      strategy/src/core.rs

+ 13 - 14
src/core_libs.rs

@@ -6,7 +6,7 @@ use strategy::{exchange_disguise, core};
 use std::sync::Arc;
 use std::sync::atomic::{AtomicBool};
 use std::time::Duration;
-use chrono::{Datelike, Local, TimeZone, Utc};
+use chrono::{Datelike, FixedOffset, Local, TimeZone, Utc};
 use tokio::sync::{mpsc, Mutex};
 use tokio::time::{sleep_until, Instant};
 use tracing::{error, info};
@@ -129,26 +129,25 @@ pub async fn init(params: Params,
     tokio::spawn(async move {
         info!("交易量统计定时任务启动(每天早上8:30)...");
         loop {
-            let now = Local::now();
+            // 定义北京时间偏移(UTC+8)
+            let beijing_offset = FixedOffset::east_opt(8 * 3600).unwrap();
 
-            // 使用 and_hms_opt 方法构建今天早上8:30的时间
-            let target_time_opt = Local.with_ymd_and_hms(now.year(), now.month(), now.day(), 14, 0, 0);
+            // 获取当前时间并转换为北京时间
+            let now = Local::now().with_timezone(&beijing_offset);
 
-            // 检查时间构建是否成功
-            let mut target_time = match target_time_opt.single() {
-                Some(time) => time,
-                None => panic!("Invalid time!"), // 处理无效时间的情况
-            };
+            // 计算今天的 8:30(北京时间)
+            let mut target_time = beijing_offset.with_ymd_and_hms(now.year(), now.month(), now.day(), 8, 30, 0).unwrap();
 
-            // 如果当前时间已经超过今天的8:30,则调整为明天的8:30
+            // 如果当前时间已经过了今天的 8:30,则目标时间调整为明天 8:30
             if now >= target_time {
                 target_time = target_time + chrono::Duration::days(1);
             }
+            info!("下一次交易量统计将在 {} 执行", target_time.timestamp());
+            // 将目标时间换算为时间戳,计算剩余等待时间
+            let duration_to_wait = (target_time.timestamp() - now.timestamp()) as u64;
+            let target_instant = Instant::now() + Duration::from_secs(duration_to_wait);
 
-            // 将目标时间转换为 Instant
-            let duration_to_wait = (target_time - now).to_std().unwrap();
-
-            sleep_until(Instant::now() + duration_to_wait).await;
+            sleep_until(target_instant).await;
             // 防止过快循环,等待一分钟后再继续下一次循环
 
             // 更新近1天(昨8点~今8点)的交易量统计

+ 4 - 1
strategy/src/core.rs

@@ -577,8 +577,11 @@ impl Core {
     }
 
     pub async fn update_trade_volume(&mut self) {
+        // 定义北京时间(UTC+8)时区
+        let timezone = chrono::FixedOffset::east_opt(8 * 3600).unwrap(); // 8 hours * 3600 seconds
+
         // 获取当前本地时间
-        let now = Local::now();
+        let now = Local::now().with_timezone(&timezone);
 
         // 获取今天早上8点
         let target_time_opt = Local.with_ymd_and_hms(now.year(), now.month(), now.day(), 8, 0, 0);