Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'cron' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
'use strict';
var CronJob = require('cron').CronJob;
var counter = 0;
new CronJob('* * * * * *', function () { // eslint-disable-line no-new
counter += 1;
}, null, true, 'America/Los_Angeles');
setTimeout(function () {
if (counter === 4) console.log('ok');
process.exit();
}, 4500);
.catch(error => {
console.error(error.message)
Healthcheck.isRunning = false
Healthcheck.error = error
// When not running job continuously stop the server
if (!options.cron) {
server.close()
}
})
}
// Setup CRON job if required
let cronJob
if (options.cron) {
console.log('Scheduling job with cron pattern ' + options.cron)
cronJob = new CronJob(options.cron, () => {
// If last job has not yet finished skip this call as we are late
if (!Healthcheck.isRunning) {
Healthcheck.nbSkippedJobs = 0
runJobWithOptions()
} else {
console.log('Skipping scheduled job as previous one is not yet finished')
Healthcheck.nbSkippedJobs++
}
})
// In case the server is forced to exit stop the job as well
server.on('close', () => {
cronJob.stop()
console.log('Stopped scheduled job with cron pattern')
})
}
// Run job
// 每晚三点
new CronJob('01 01 03 * * *', function() {
// 更新实验室里的Github数据
updateLabsDataFromGithub.all()
// 更新个人Github信息
myGithubData.update()
// 更新剧中人的朋友圈数据
updateMoment.sync()
// 更新720云数据
my720Data.update()
// 更新图虫数据
myTuchongData.update()
}, null, true, 'Asia/Hong_Kong')
// 每晚三点零十分
new CronJob('01 10 03 * * *', function() {
// 清除全部缓存
app.cache.clear()
}, null, true, 'Asia/Hong_Kong')
}
const computeFromInterval = () => {
debug('[%s:%s] computing next run via interval [%s]', this.attrs.name, this.attrs._id, interval);
let lastRun = this.attrs.lastRunAt || new Date();
lastRun = dateForTimezone(lastRun);
try {
const cronTime = new CronTime(interval);
let nextDate = cronTime._getNextDateFrom(lastRun);
if (nextDate.valueOf() === lastRun.valueOf()) {
// Handle cronTime giving back the same date for the next run time
nextDate = cronTime._getNextDateFrom(dateForTimezone(new Date(lastRun.valueOf() + 1000)));
}
this.attrs.nextRunAt = nextDate;
debug('[%s:%s] nextRunAt set to [%s]', this.attrs.name, this.attrs._id, this.attrs.nextRunAt.toISOString());
} catch (e) {
// Nope, humanInterval then!
try {
if (!this.attrs.lastRunAt && humanInterval(interval)) {
this.attrs.nextRunAt = lastRun.valueOf();
debug('[%s:%s] nextRunAt set to [%s]', this.attrs.name, this.attrs._id, this.attrs.nextRunAt.toISOString());
} else {
this.attrs.nextRunAt = lastRun.valueOf() + humanInterval(interval);
debug('[%s:%s] nextRunAt set to [%s]', this.attrs.name, this.attrs._id, this.attrs.nextRunAt.toISOString());
const computeFromInterval = () => {
debug('[%s:%s] computing next run via interval [%s]', this.attrs.name, this.attrs._id, interval);
let lastRun = this.attrs.lastRunAt || new Date();
lastRun = dateForTimezone(lastRun);
try {
const cronTime = new CronTime(interval);
let nextDate = cronTime._getNextDateFrom(lastRun);
if (nextDate.valueOf() === lastRun.valueOf() || nextDate.valueOf() <= previousNextRunAt.valueOf()) {
// Handle cronTime giving back the same date for the next run time
nextDate = cronTime._getNextDateFrom(dateForTimezone(new Date(lastRun.valueOf() + 1000)));
}
this.attrs.nextRunAt = nextDate;
debug('[%s:%s] nextRunAt set to [%s]', this.attrs.name, this.attrs._id, new Date(this.attrs.nextRunAt).toISOString());
// Either `xo` linter or Node.js 8 stumble on this line if it isn't just ignored
} catch (error) { // eslint-disable-line no-unused-vars
// Nope, humanInterval then!
try {
if (!this.attrs.lastRunAt && humanInterval(interval)) {
this.attrs.nextRunAt = lastRun.valueOf();
debug('[%s:%s] nextRunAt set to [%s]', this.attrs.name, this.attrs._id, new Date(this.attrs.nextRunAt).toISOString());
} else {
function computeRecurringDates (pattern, { startDate, endDate, timezone = 'UTC' } = {}) {
if (_.isNil(timezone)) timezone = 'UTC'
if (!isDateString(startDate) || !isDateString(endDate)) {
throw new Error('Expected start and end dates')
}
if (endDate < startDate) {
throw new Error('Invalid dates')
}
const cronTime = new CronTime(pattern, timezone)
let continueLoop = true
const dates = []
let cronISODate = new Date(new Date(startDate).getTime() - 1) // start from `startDate` minus 1 millisecond
while (continueLoop) {
// `_getNextDateFrom` is a private method from `CronTime.prototype`
// Please check its availability when upgrading the library `cron`
const cronMomentDate = cronTime._getNextDateFrom(cronISODate, timezone)
cronISODate = cronMomentDate.toISOString()
continueLoop = cronISODate < endDate
if (continueLoop) {
dates.push(cronISODate)
}
var announceMatchComplete = function (match) {
var vs = match.homeTeam + ' vs ' + match.awayTeam;
var stadium = match.data.c_Stadidum + ', ' + match.data.c_City;
var text = stopExpression + ' ' + slackLink(vs, match.url) + ' (' + stadium + ')';
announce(text);
delete(activeMatches[match.data.n_MatchID]);
};
/**
* Sends a score summary message to slack.
*/
var announceScore = function (match) {
announce(match.homeTeam + ' (' + match.score + ') ' + match.awayTeam);
};
var cronJob = cron.job("*/5 * * * * *", function(){
// Get Match list
requestify.get('http://live.mobileapp.fifa.com/api/wc/matches').then(function(response) {
var matches = response.getBody().data.second;
async.filter(matches, function(item, callback) {
callback (item.b_Live == true || activeMatches[item.n_MatchID]);
}, function(results){
for (var i = 0; i < results.length; i += 1) {
if (activeMatches[results[i].n_MatchID]) {
match = activeMatches[results[i].n_MatchID];
} else {
match = new Match(language);
match.on('startMatch', announceMatchStart);
init: function () {
// each day at 10 AM
const cronJob = cron.job("0 0 10 * * *", () => {
sendNotification();
});
cronJob.start();
},
const cron = require('cron');
const fetch = require('node-fetch');
const { promisify } = require('util');
const fs = require('fs').promises;
const exec = promisify(require('child_process').exec);
const beautify = require('js-beautify').js;
const chunker = require('./chunker');
const searcher = require('./searcher');
const logger = require('./logger');
const jsStyle = require('../style');
const jsonStyle = {
"indent_size": "2",
"eol": "\r\n",
};
const detector = cron.job("0 */30 * * * *", async () => {
try {
const gameConsts = await (await fetch('http://203.104.209.7/gadget_html5/js/kcs_const.js')).text();
const version = gameConsts.match(/\d\.\d\.\d\.\d/)[0];
const currentVersion = await fs.readFile('../version');
if (version !== currentVersion.toString()) {
logger.info(`Detected main.js v${version}`);
const script = await (await fetch(`http://203.104.209.71/kcs2/js/main.js?version=${version}`)).text();
await fs.writeFile(`../raw.js`, script);
await fs.writeFile(`../main.js`, beautify(script, jsStyle));
await fs.writeFile('../version', version);
const functions = /}\((\[function.*)\).default/s.exec(script)[1];
chunker(eval(functions)); // haven't find a better way to parse array of functions
const start = /=\s*(\d*)\)\s*}\(\[/.exec(script)[1];
await fs.writeFile('../tree.json', beautify(JSON.stringify(searcher(start)), jsonStyle));
const { stdout, stderr } = await exec(`"../push.sh" "Update: main.js v${version}"`);
logger.info(stdout);
init : function() {
// every hour
var cronJob = cron.job("0 0 */1 * * *", function() {
checkForNewPhotos(config);
});
cronJob.start();
checkForNewPhotos(config);
},