2017-07-25 88 views
0

我需要一个函数来初始运行,然后在下午12点和上午12点重新运行。如果有任何影响,我使用VueJS。设置每12小时的时间间隔

fetch_datetime() 
{ 
    axios.get('/api/core/datetime').then((response) => { 
     this.datetime = response.data; 
     this.set_interval(); 
    }); 
}, 

set_interval() 
{ 
    var current_date = new Date(); 
    var hours = current_date.getHours(); 
    var minutes = current_date.getMinutes(); 
    var seconds = current_date.getSeconds(); 
    if(hours == 12 && minutes == 0 && seconds == 0 || hours == 0 && minutes == 0 && seconds == 0) 
    { 
     this.fetch_datetime(); 
    } else 
    { 
     if(hours >= 12) 
     { 
      setTimeout(this.fetch_datetime, (1000 * (60 - seconds) * (60 - minutes)) + (1000 * 60 * (24 - hours - 1) * 60)); 
     } else 
     { 
      setTimeout(this.fetch_datetime, (1000 * (60 - seconds) * (60 - minutes)) + (1000 * 60 * (12 - hours - 1) * 60)); 
     } 
    } 

但是,这不是按预期方式工作,并且该功能运行得很早,然后在小时内运行多次。

+3

谁将打开浏览器12小时后再次运行该功能? – Pete

+0

这个想法是,如果用户在11:50访问该站点,该功能需要在12:00重新运行。 – Imagine17

+1

更好的问题是:Imagine17真的等了12个小时,看看它是否有效:D – SkryptX

回答

1

这是一个非常简单的功能,可以做你想做的事情。它应该适合你的用例(几分钟后刷新),但不要指望它在浏览器更改上具有很强的适应性。

// Takes an array of hours as number and a function to execute 
 
function executeOnHours(hours, callback) { 
 
    callback(); // First, execute once 
 
    let now = new Date(); 
 
    const hoursWithToogle = hours.map(h => { 
 
    return { 
 
     value: h, 
 
     executedToday: now.getHours() === h // Don't run now if already on the given hour 
 
    } 
 
    }); 
 
    setInterval(() => { 
 
    now = new Date(); 
 
    const triggers = hoursWithToogle.filter(h => { 
 
     if (!h.executedToday && h.value === now.getHours()) { 
 
     return h.executedToday = true; 
 
     } else if (h.value !== now.getHours()) { 
 
     h.executedToday = false; // Clean the boolean on the next hour 
 
     } 
 
    }); 
 
    if (triggers.length) callback(); // Trigger the action if some hours match 
 
    }, 30000); // Fix a precision for the check, here 30s 
 
} 
 

 
executeOnHours([0, 12], function() { 
 
    console.log('Something is done'); 
 
});

如果你正在寻找一个更强大的解决方案,你也可以使用later.js,声称能在浏览器中运行,并提供一个全功能的cron接口,在集束大小的成本。

+0

@ Imagine17请注意,我的代码中存在拼写错误(第一次getHours上缺少括号)。 – Cobaltway

0

我会首先计算到下一个上午12点/下午的距离,第一次运行后您可以在每次通话中添加12小时或创建间隔。

要获得的距离,你可以使用的Date.now差和时刻运行第一次运行:

var n = new Date() 
if(n.getHours()>=12){ 
    n.setHours(24); 
}else{ 
    n.setHours(12); 
} 

在此之后将所有小单位一个多小时到零。

初始呼叫后: setInterval(this.fetch_datetime, 12 * 60 * 60 * 1e3)

还有一个VUE插件,它提供了时间间隔和回调https://www.npmjs.com/package/vue-interval

您还应该记住的setTimeout和setInterval都没有绝对正确的帮助。他们可能会提早或延迟触发几毫秒。因此,计算与下一个执行时刻的差异可以触发函数double。