running a task on particular datetime? - firebase

I am wondering how to write a proper code for runnning a job on particular date on Firebase.
For cron-type job, I know these situation should be realized as follows:
exports.scheduledFunctionCrontab = functions.pubsub.schedule('5 11 * * *')
.timeZone('America/New_York') // Users can choose timezone - default is America/Los_Angeles
.onRun((context) => {
console.log('This will be run every day at 11:05 AM Eastern!');
return null;
});
but this for "repeated" job and not for "one-time" job.
Is there any way to run particular job on a particular date using Firebase?
Thanks!

I found a great answer here by myself.
https://medium.com/firebase-developers/how-to-schedule-a-cloud-function-to-run-in-the-future-in-order-to-build-a-firestore-document-ttl-754f9bf3214a

Related

Incremental Static Regeneration doesn't work without redeploying

This is my very first time building and deploying a website so bear with me if this is a dumb question. I'm building a Heardle style clone. The idea is that every day there's a new song and people have 6 guesses to figure out which song it is from short clips of the song. Every part of this seems to work with one major exception -- I can't seem to reload today's song dynamically.
I have a function:
export async function getStaticProps() {
const allSearchableSongs = songHelper.getSongData()
const todaysSong = await songHelper.getTodaysSong()
const songURLs: string[] = (todaysSong) ? await songHelper.getTodaysSongClips(todaysSong!) : []
let valid = false
if (songURLs) {
valid = true
}
return {
props: {
allSearchableSongs,
todaysSong,
songURLs,
valid
},
revalidate: 10
};
}
Note that getTodaysSong() and getTodaysSongClips() both make calls to AWS to get data from S3. Whenever I rebuild the website this works well. However, I would like for this to refresh after 60 seconds so that nobody is ever looking at a stale website. But this doesn't change ever. The song is always out of date until I redeploy. I've checked to make sure that the data is changing daily and that's all well and good -- but the website doesn't ever reload.
I'm currently hosting this on Vercel.
What am I doing wrong? How can I ensure that this reloads after 60 seconds?

Unexpected behaviour in scheduled firebase function

I have a firebase scheduled function with the crontab expression: 0 2-22/2 * * *
As I understand it, this function should be run every two hours every day, apart from at midnight.
However, the function was just triggered at midnight, so I must be doing something wrong.
Here is the code I wrote for the function scheduling:
exports.everyTwoHourRunGame = functions
.runWith({
timeoutSeconds: 540,
})
.pubsub.schedule("0 2-22/2 * * *")
.onRun(async () => {
On the firebase website, I can view the logs for the function and see that it ran the second after 00:00, other than this it has been working fine, executing every two hours as expected.
Any help would be much appreciated.

TypeOrm QueryBuilder dynamic auto delete function with crons job not working

Token for email verification is created with User registration and needs to be deleted from database within 24 hours with crons job help. In a delete function using query builder, token gets deleted only if date value is manually provided in form of string: {delDate: "2021-02-08T17:59:48.485Z" }. Here, all tokens with date before or equal 2021-02-08 get deleted, and is working fine. But thats a static input, manually put in hard code!
Since this must be a dynamic input, I set up variable 'delTime',which stores current date minus 24 hrs in it, but it seems .where condition will not take a variable as value, and will not delete, as: {delDate: deltime}. In fact, 'delDate' consoles exactly the info I need, but it will only work in form of string.
There is a ton of content online teaching how to delete stuff with a static value in typeorm querybuilder, but so hard to find with dynamic values....
How else can I make this work in a dynamic way ?
async delete(req: Request, res: Response){
try {
const tokenRepository = getRepository(Token);
var delTime = new Date();
delTime.setDate( delTime.getDate() - 1 );
console.log(delTime) //consoles 24 hors ago
await tokenRepository
.createQueryBuilder()
.delete()
.from(Token)
.where("tokenDate <= :deleteTime", { deleteTime: delTime})//value dynamically stored in variable does not delete
//.where("tokenDate <= :deleteTime", { deleteTime: "2021-02-08T18:01:10.489Z"})//static hard code value deletes
//.where("tokenDate <= :delTime", { delTime})//Variable put this way will not work either...
.execute();
} catch (error) {
res.status(404).send("Tokens not found");
return;
}
res.status(200).send('Tokens deleted successfuly');
}
Your parameterized query looks correct.
Switch on TypeOrm Query Logging to see the generated SQL, maybe you will be able to see what's going wrong. Paste the generated SQL into the SQL query console to debug.
Alternatively you can write your delete query without parameters and let Sqlite calculate current date -1 day:
.where("tokenDate <= DateTime('Now', '-1 Day'"); // for Sqlite
Note 1: Sqlite DateTime('Now') uses UTC time, so your tokenDate should use UTC also.
Note 2: This syntax is specific to Sqlite, you can do the same in other databases but the syntax is different, e.g. Microsoft SQL Server:
.where("tokenDate <= DATEADD(day, -1, SYSUTCDATETIME()); // for MS SQL Server

Set a wordpress cron job to hit a url every 2 minutes

Hi I have a url which imports data from csv to database on wordpress.I want this to run every 2 minutes .Is tried a plugin for this cron job scheduer but this did not work.
How can I write a action script function make this possibe.Please help
You can do the following
First you need to add the 2m interval to the schedule
add_filter('cron_schedules', 'my_schedules');
function my_schedules($schedules)
{
$schedules['once_every_2m'] = array('interval' => 120, 'display' => 'Once every 2 minutes');
return $schedules;
}
Then you add your job using newly created interval
if (!wp_next_scheduled('name_of_your_job'))
{
wp_schedule_event(1481799444, 'once_every_2m', 'name_of_your_job');
}
add_action('name_of_your_job', 'function_that_should_be_executed');
function function_that_should_be_executed()
{
//do what you need to do
}
Also, keep in mind, due to how WP cron works, it might be in accurate with timing. Docs

Momentjs in meteor- reactivity?

Have been using https://github.com/acreeger/meteor-moment in meteor and it works well, however is there a way to make the output of moment reactive so that it counts up "3 seconds ago", "4 seconds ago", etc?
Rather than using a new Session variable for each individual timer, I would create a single Tracker.Dependency which is flagged for changes every second (or perhaps every 10 seconds), then depend on this whenever you want to depend on the current time.
var timeTick = new Tracker.Dependency();
Meteor.setInterval(function () {
timeTick.changed();
}, 1000);
fromNowReactive = function (mmt) {
timeTick.depend();
return mmt.fromNow();
}
Template.example.helpers({
example: function () {
return fromNowReactive(moment().startOf('hour'));
}
});
This is the approach taken by mizzao:timesync, which is a useful package you can use if those fromNows are based on server-side timestamps. One reason to not use client-generate timestamps is that these may be out of sync, resulting in strings like 5 seconds from now for a post that was just made. mizzao:timesync allows server-generated timestamps to be used everywhere, and also groups different reactivity intervals together efficiently.
You can now use the package copleykj:livestamp. (github | atmosphere)
Install it like this:
meteor add copleykj:livestamp
It has a dependency on momentjs:moment so it will bring that along automatically. It installs a universal helper that is available anywhere and can be passed a date object.
You can use it in a template like this:
<li>Regular: {{date}} </li>
<li>Livestamp: {{livestamp date}}</li>
Here's a working demo in MeteorPad
Thanks for the replies everyone, I found a mrt package which does the job atmospherejs.com/package/livestamp
Use setTimeout and Session to store your variable.
Something like this (in your lib file):
var updateTime = function () {
var time = moment().startOf('hour').fromNow(); // 22 minutes ago
Session.set('timeFromNow', time);
setTimeout(updateTime, 60 * 1000); // 60 seconds
});
updateTime();
Then, in your template:
Template.t.timeFromNow = function () {
return Session.get('timeFromNow');
}
When setTimeout triggered to update Session variable, the template is updated.

Resources