I would like to make bot that in specific time every day will for example message but i want that the bot can still response to commands. Is there any node.js library or some function.
You can use the cron package to do this.
You first have to import CronJob:
const { CronJob } = require('cron');
If you want to scedule a message at 17:18 everyday, you define a CronJob like this:
const job = new CronJob('0 18 17 * * *', () => {
//send a message
});
and start it:
job.start();
the format for the string is 'sec min hour day of month month day of week'. You use * if all values of that parameter is accepted. Your callback function will be called everytime all 6 of the paremeters match the current time. The sec parameter must not be *, or else the message would get sent every second in that minute.
Related
i want to display when a user last seen online by time like whatsapp
using xmpp and angular
i made an xmpp request and i get user last seen by second and i want to convert it to time
what i got :
user last seen 903 seconds ago
what i want :
user last seen at 11:30 pm
Last Activity Response by Server¶
<iq from='juliet#capulet.com'
id='last1'
to='romeo#montague.net/orchard'
type='result'>
<query xmlns='jabber:iq:last' seconds='903'>Heading Home</query>
</iq>
If you take the seconds value you received from server to a variable, you can do it like below.
const timeInSeconds = getValueFromServer();
const lastLoggedInTime = new Date(Date.now() - timeInSeconds * 1000);
In your html template, you can use lastLoggedInTime variable to show the date.
I am creating a function on my server which is supposed to trigger daily, but not only does it not trigger as expected it triggers every time the server is reset (which it did not do yesterday). The data only needs updated once a day and rapidapi is pay per api call after 100 calls a day, so I'm really trying to get this scheduled job working.
I've only tried node-schedule on my server, which has a dependency of CRON (which is why scheduleJob is using the CRON format). Originally the function triggered as fast as my computer could refresh the server, so I know the scheduleJob is stopping the API call from being constant.
schedule.scheduleJob('* * */23 * *', function () {
console.log('Daily API call initiated.');
unirest.get("https://unogs-unogs-v1.p.rapidapi.com/aaapi.cgi?q=get:exp:US&t=ns&st=adv&p=1")
.header("X-RapidAPI-Host", "unogs-unogs-v1.p.rapidapi.com")
.header("X-RapidAPI-Key", `${keys.RICHARD_UNOGS_KEY}`)
.end(function (result) {
console.log(result.status, result.headers);
//console.log(result.body) to see all data
let data = JSON.stringify(result.body)
fs.writeFile('./movieData.json', data)
});
})
Is there a better way to write this function or achieve the desired results? I only need it triggering once per day, but my computer isn't on 24/7. Since I'm still developing the app, I don't think hosting the server on Heroku or another platform is time-efficient, but I'm more than willing to try it if it'll solve my issue.
The main goal is to tell my server to run it once a day, but to check if it was run in the last 24 hours. If it hasn't been run, run it.
ANSWERED BY jakemingolla: My CRON expression was incorrectly formatted for my intended use. * * */23 * * has the function triggering on every 23rd day (today is the 24th, +1 for index value) with no limitation or other value. That's why my function was calling constantly today. I changed my CRON expression to 15 9 * * * to trigger my API call every morning at 0915 hours.
I'm not sure your CRON format is correct based on https://crontab.guru. Based on * * */23 * *, that would correspond to "“At every minute on every 23rd day-of-month", which does not sound like what you want.
For example, the CRON string 0 0 * * * * is every day at midnight. I would update that CRON string to see if it helps alleviate the problem.
In my (express.js based) loopback app I want to schedule a task to run every 1 second. It should count every open ticket, and if they already open for a certain time, then an email should be sent. Below is a simplified code.
The problem, that 'scheduleJob' is logged, as expected, but the number of tickets is not. I think it is a context problem. How should I log the number of the found ticket? How should I communicate back from count 's callback to the schedule 's callback?
var schedule = require('node-schedule');
module.exports = function(app) {
var Ticket = app.models['Ticket']
var j = schedule.scheduleJob('* * * * * *', function(){
console.log('scheduleJob')
Ticket.count(function(err, count){
if (err) {console.log(err)}
console.log(count)
})
});
};
Do not count all the open ticket like that - It costs a lots of resources.
You should keep the number of ticket in your node.js and increase/decrease it. If you have multiple processes interacting with the database, makes one of them your master and make it handle this task.
About your problem, it seems that the library node-schedule do not support asynchronous calls.
Algorithm
At your program start, look up at the ticket in your database and retrieve the next timestamp when you should send an email.
Example, you want to send an email if a ticket is open for 1 hour, and your database have :
ticket 1 / 10 min
ticket 2 / 40 min
So your next mail should be sent in 20 min (60 min - 40 min).
use setTimeout() to wake up your node in 20 min. When you wake up, send the mail, and look at your database again for the next mail to send.
Recalcul your setTimeout if there is a new Ticket inserted in your database or If one get removed/updated.
I am trying to update a database field on a MongoDB collection using Meteor at an exact time -- say 12:00 AM every Monday.
How should I go about doing this?
I am trying matching the day of the week and the exact time number but I can't seem to make it work for the server to do this more than once without using a loop that will make the website freeze.
If you can install a cron-job npm module, like: npm install cron, than you could set up a cron job with a Monday-only pattert, to call your db update code.
var CronJob = require('cron').CronJob;
var job = new CronJob('00 00 12 * * 1', function() {
/*
* Runs every weekday Monday at 12:00:00
*/
}, function () {
/* DB update code */
}
);
Docs available at https://github.com/ncb000gt/node-cron, if you need to fine tune your cron pattern or other options.
so far I have tried many different tutorials to get this to work but so far I have not been able to achieve this.
Currently I have a nodejs app that sends messages to the Service Bus Queue and another nodejs that polls continuously. My goal is to send a message to the queue with a specific time and date on which the polling system can process the message.
My results so far is that as soon as I send the message, it becomes visible and it is processed right away, here is what I have
//made some changes after the first suggestion, but still does not work
//what I'm doing here is offsetting the time difference with UTC(im in GMT-7 tz) by adding it manually
//(this is just a test so if this would have worked I would have made it more elegant)
var scheduled_time = new Date().valueOf() + ((60000*60)*7.5);
var current_time = Date.now();
console.log(scheduled_time, current_time);
var message = {
body: 'Time ' + current_time.toString(),
brokerProperties:{
ScheduledEnqueueTimeUtc: scheduled_time,
TimeToLive: 8
},
customProperties: {
testproperty: 'TestValue'
}};
serviceBus.sendQueueMessage('myqueue', message, function(error){
if(!error){
// message sent
console.log('message sent');
}
});
My receiver is very simple
function receiveMessages() {
serviceBus.receiveQueueMessage(queue,
function (error, message) {
if (error) {
console.log(error);
} else {
console.log('Process after ' + message.brokerProperties.ScheduledEnqueueTimeUtc);
}
});
};
so far I have read the GitHub page with the description of the properties of the message and it seems correct to what I have but it still does not work.
Thank you
Date.now() returns a date in your timezone, not in UTC. You need to convert it to UTC. This question can help you with that.
It appears one of the problems is with the format of ScheduledEnqueueTimeUtc. I was able to successfully delay queue messages in Azure Service Bus from Node.js using moment.js to adjust and format the date:
// Delay message by 1 hour
var scheduled_time = moment().utc().add(1, 'hour').format('M/D/YYYY H:mm:ss A');
var message = {
body: 'Time ' + Date.now().toString(),
brokerProperties: {
ScheduledEnqueueTimeUtc: scheduled_time
},
customProperties: {
testproperty: 'TestValue'
}
};
The Service Bus docs and JavaScript SDK unfortunately don't appear to mention anything about what format ScheduledEnqueueTimeUtc should be in other than that the type is a String. However, if you look at code examples in .NET languages, the value is being passed using DateTime.toString() which defaults to the 'G' general date and time format specifier (example: 5/1/2009 9:00:00 AM). Following these examples, we can duplicate the format using something like moment.js: "M/D/YYYY H:mm:ss A". As TheDude mentioned, bear in mind the value must be in UTC and not local time.
Also, your TimeToLive value of 8 may be too short to allow processing, and note that delaying or scheduling a queue using ScheduledEnqueueTimeUtc doesn't guarantee that it will be processed at the specified date and time. It only guarantees the message won't be processed beforehand. See remarks in https://msdn.microsoft.com/en-us/library/microsoft.servicebus.messaging.brokeredmessage.scheduledenqueuetimeutc.aspx
Per my experience, I think you could try to check the region for the Service Bus and your Node.js Application on Azure for keeping the same regions.
More information, please refer to the broker properties for BrokeredMessage Class https://msdn.microsoft.com/en-us/library/azure/microsoft.servicebus.messaging.brokeredmessage.aspx.
The above example uses the azure-sb package which in turn uses HTTP to talk to Azure Service Bus. The newer #azure/service-bus package uses AMQP and is more performant than the azure-sb.
If using the #azure/service-bus package, then you can set the scheduledenqueuetimeutc directly on the message and send it. This property is of type Date