setInterval() and setTimeout() do nothing on heroku - node.js

My Node.js app works as intended and runs without errors on VSCode. However, setInterval() and setTimeout() do nothing once my app runs on heroku. I knew this because I wrote console.log() everywhere and looked at the heroku log of my app. None of the console.log() statements inside a setInterval() or setTimeout() were executed.
Surprisingly, all other functions of this app worked on heroku.
Here is the segment of code.
var refreshIntervalId = setInterval(() => {
config = require("./config.json");
// console.log("index line 44: entered loop");
if (config["reminder#" + fixedCount] == undefined) return clearInterval(refreshIntervalId);
config["reminder#" + fixedCount]["time"] -= 5 * 60 * 1000;
if (config["reminder#" + fixedCount]["time"] > 0) updateJson();
}, (5 * 60 * 1000));
setTimeout(() => {
const color = "#" + hexCodes[~~(Math.random() * hexCodes.length)], userID = config["reminder#" + fixedCount]["user"];
const userObject = client.users.cache.get(userID);
let sendReminder = new Discord.MessageEmbed()
.setTitle(`Reminder to ${userObject.username.split("#")[0]}`)
.setColor(color)
.setDescription(config["reminder#" + fixedCount]["content"]);
userObject.send({embeds: [sendReminder]}).catch(err => { });
delete config["reminder#" + fixedCount];
updateJson();
}, config["reminder#" + fixedCount]["time"]);
Any idea why this happened?

Related

Node fluent-ffmpeg screenshots on Windows

The fluent-ffmpeg package has a function that will create screenshots at even intervals in a video for a given count. The problem with this is that it often spawns a ENAMETOOLONG error on Windows.
To get around this, I copied the relevant parts of the source code that I needed and instead of running it all as one long command, split it up into n many commands (where n is the amount of screenshots).
This seems to work at first. It (sometimes) gets the first screenshot, but then it throws the same ENAMETOOLONG error. How can I get around this?
Here is what I have attmpted:
const count = 50 // just an example
const dest = path.join(os.tmpdir(), `screenshots_${Date.now()}`)
const interval = 100 / (1 + count)
let timemarks = Array(count)
.fill(0).map((_, i) => (interval * (i + 1)) + '%')
.map(mark => {
if (('' + mark).match(/^([\d.]+)%$/)) {
// #ts-ignore
return videoDuration * parseFloat(mark) / 100
} else {
return mark
}
})
.map(mark => {
if (typeof mark === 'number') {
return mark
}
if (mark.indexOf(':') === -1 && mark.indexOf('.') >= 0) {
return Number(mark)
}
const parts = mark.split(':')
let secs = Number(parts.pop())
if (parts.length) {
secs += Number(parts.pop()) * 60
}
if (parts.length) {
secs += Number(parts.pop()) * 3600
}
return secs
})
.sort((a, b) => a - b)
// my first attempt:
for (const mark of timemarks) {
this.video
.screenshot({
count: 1,
folder: dest,
timemarks: [mark],
})
}
// second attempt:
let i = 0
for (const mark of timemarks) {
const filename = `frame_${i.toString().padStart(count.toString().length, '0')}.jpg`
this.video
.setStartTime(mark)
.output(path.join(dest, filename))
.frames(1)
.run()
i++
}
For context, this.video is just ffmpeg(videoFilePath).
My first attempt, as I previously stated, just throws the same error and doesn't really get anywhere. Sometimes I get the first screenshot, most times I do not.
The second attempt doesn't even do anything. It seems to take it's time doing something, but I don't actually get any screenshots. If they saved anywhere, I don't know where.
Is anyone able to help me with this?

How to prevent code from excecuting multiple times

This code ends up spamming messages for one second every time it runs. Does anyone know to prevent that? the variable count is the amount of messages sent in the last hour, and my goal is if more then 15 were sent in the past hour then to send a message. Here is the code I tried:
var count = await keyv.get('messagecount')
const sendtochan = await rotate.guild.channels.cache.get('760626595332358205');
cron.schedule('0 0 * * * *', async () => {
if (count > 14 && !rotate.author.bot) {
keyv.set('messagecount', 0)
const sendtochan = await rotate.guild.channels.cache.get('760626595332358205');
sendtochan.send(`This channel's current topic is: **${await keyv.get('topic')}**`);
return
}
if (count < 14 && !rotate.author.bot) {
keyv.set('messagecount', 0)
return
}
});

Cannot read property 'query' of undefined - In Vanilla Chrome Extension [duplicate]

This question already has answers here:
"Cannot read property of undefined" when using chrome.tabs or other chrome API in content script
(4 answers)
Closed 2 years ago.
I'm trying to program a simplistic application that runs a timer in content.js, but also sends an alert of the web page url. After looking at the documentation, I came up with this:
content.js
chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT},
function(tabs){
alert(tabs[0].url);
}
);
let message = "";
console.log("Death Timer Running...");
let body = document.getElementsByTagName("body")[0];
let div = document.createElement("DIV");
div.setAttribute("CLASS", "timer");
let text = document.createElement("P1");
text.setAttribute("ID", "myText");
text.setAttribute("CLASS", "timerText");
div.appendChild(text);
body.appendChild(div);
var endDate = new Date("Oct 07, 2085 16:37:52").getTime();
var myfunc = setInterval(function() {
// code goes here
var now = new Date().getTime();
var timeLeftSeconds = parseInt((endDate - now)/1000);
var timeLeftMinutes = parseInt(timeLeftSeconds/60);
var timeLeftHours = parseInt(timeLeftMinutes/60);
var timeLeftDays = parseInt(timeLeftHours/24);
var timeLeftYears = parseInt(timeLeftDays/365);
let secondsLeft = timeLeftSeconds;
var yearsLeft = timeLeftYears;
secondsLeft -= (yearsLeft * 365 * 24 * 60 * 60)
var monthsLeft = parseInt(secondsLeft/(60*60*24*30))
secondsLeft -= (monthsLeft * 60 * 60 * 24 * 30)
var daysLeft = parseInt(secondsLeft/(60*60*24))
secondsLeft -= (daysLeft * 60 * 60 * 24)
var hoursLeft = parseInt(secondsLeft/(60*60))
secondsLeft -= (hoursLeft * 60 * 60)
var minutesLeft = parseInt(secondsLeft/(60))
secondsLeft -= (minutesLeft * 60)
message = (yearsLeft.toString() + "y, " + monthsLeft.toString() + "mo, " + daysLeft.toString() + "d, " + hoursLeft.toString() + "h, " + minutesLeft.toString() + "mi, " + secondsLeft.toString() + "s")
console.log(message)
document.getElementById("myText").innerText = message;
}, 1000)
manifest.json
{
"manifest_version":2,
"name":"Death Timer",
"version":"0.1",
"description":"A timer that helps you put things into perspective.",
"permissions":[
"activeTab", "tabs"
],
"content_scripts": [
{
"matches":[
"<all_urls>"
],
"js":["content.js"],
"css":["content.css"]
}
]
}
The timer is working fine, however when I try to implement the retrieval of the active tab, I receive this this error:
Uncaught TypeError: Cannot read property 'query' of undefined
at content.js:2
Why would this be happening? I've looked at other SO posts which all had the same problem - but those appeared to be due to the accessing of outside resources. My app is vanilla, so this shouldn't be an issue.
The chrome.tabs API is only available in background and popup scripts. That's why it is returning tabs as undefined.
If you want to use the API, you can send a message from the content script to the background, which will use the tabs API, then send the result back to the content script.

How Can I Console.log countdownjs module via node.js

I'm using countdownjs module
, How Can I Console.log countdownjs for 3 days later, via node.js?
Here is a small example how you can use the countdown module:
var now = new Date();
var durationInDays = 3;
var durationInMilliseconds = (durationInDays * 24 * 60 * 60 * 1000);
var future = now.getTime() + durationInMilliseconds;
var countdownInfo = countdown(now, future);
// print it once
console.log(countdownInfo.toString());
// print it every 5 seconds
function repeatedPrint() {
setTimeout(function () {
// you have to provide a new start date to get updated information
countdownInfo = countdown(new Date(), future);
console.log(countdownInfo.toString());
repeatedPrint();
}, 5 * 1000);
}
repeatedPrint();

Create a Scheduled Job on Startup With Express

I'm just getting into Express and have ran into an issue. I have an app serving a REST API. That is all working fine. But I wanted to add a scheduled job using node-schedule (https://www.npmjs.com/package/node-schedule). I have implemented this module:
var schedule = require('node-schedule');
var scheduler = {
scheduleJob: function(monitor) {
var job = schedule.scheduleJob('* * * * *', function(){
monitor.check();
});
return job;
}
}
module.exports = scheduler;
In app.js I have added the following to the bottom since I found a single stack overflow question that was similar. This did not work for me:
app.on('listening', function () {
console.log("App started, gathering monitors");
var allMonitors = queries.getAllMonitorsInt();
for (var i = 0; i < allMonitors.length; i++) {
console.log("Monitor found: " + allMonitors[i].name);
shdlr.scheduleJob(allMonitors[i]);
}
});
I don't even get the "App started..." log message.
Am I doing this the right way or am I way off target?
The scheduler should be placed inside of app.listen callback, like this:
app.listen(3000, function () {
console.log("App started, gathering monitors");
var allMonitors = queries.getAllMonitorsInt();
for (var i = 0; i < allMonitors.length; i++) {
console.log("Monitor found: " + allMonitors[i].name);
shdlr.scheduleJob(allMonitors[i]);
}
});
Express doesn't support listening event, see an issue.

Resources