Will scheduled task run if the user is not opening the application? - javascript

The situation:
I have a program that records student's payments, (made entirely with HTML, CSS and javascript), I would like it to calculate the amount of students that stopped the lessons, automatically, around the end of the month (by automatically I mean without the user having to press any buttons to get that info).
My question is:
If for example I schedule the function to run on the 29 of every month, and that day the user does not open the program, does the function get executed anyway or not?
The program is an off line program, made to be downloaded once and run always, no need to connect again to the web if the user decides it.
I would do something like:
var thisMoment = new Date(),//creates a date object
currentDay = thisMoment.getDate(); //this would give me the day at that moment.
if(currentDay == 29) { }//code to be executed here
I know I could just try it, but I would have to wait for a day, or rewrite the code to schedule something some minutes ahead, but I would miss all the juicy information you are probably going to share here hahaha.
Any help appreciated! :)

Unless there's some sort of server-side component, your HTML app effectively ceases to exist as soon as the user closes it. Nothing will happen if it's not open.
To do this kind of thing, you will either need a server application that's continuously running, or some sort of cron job that runs an application/script on the server at the desired time. Then, you will need to have your frontend application communicate with this server, most likely through some kind of REST API.

Related

Javascript - how to change/fix/sync system time for browser session

Let's say my website uses a 3rd party javascript library which requires the user's system time to be correct (synced with the server time) within a couple minutes.
Surprisingly many users have their device clocks set wrong by more than a couple minutes and are unable and/or unwilling to fix it. Is there any way I can fix it for them, at least inside a browser session?
I know how to get the correct time, but how can I "set" it into the browser session, so that it can be returned next time a 3rd party library asks for the current time?
For example, I would like to have something like this in my code:
let tWrong = new Date(); // contains wrong system time that the user has on their device
let tCorrect = getCorrectTimeFromServer(); // contains correct time fetched from a server
Date.someFunctionToSetGlobalTime(tCorrect); // how to do this?
And then, somewhere deep in the 3rd party library where I do not have access to change the code, this would happen:
let t = new Date(); // t already contains the correct server time
And if this is not possible, how do websites normally deal with this issue? It must be incredibly common, for example when issuing JWT tokens with an expiry time, that one side thinks the token is already expired as soon as it is issued, due to wrong system time.
Answering my own question, in case someone runs into the same problem.
I found out the 3rd party library was using the getUTCHours, getUTCMinutes and getUTCSeconds functions, so instead of setting the time itself, I ended up overriding these functions like this. It feels ugly, but it works:
Date.prototype.getUTCHours = getMyCorrectUTCHours;
Date.prototype.getUTCMinutes = getMyCorrectUTCMinutes;
Date.prototype.getUTCSeconds = getMyCorrectUTCSeconds;

Executing codes on website without the website being accessed PHP

I don't know if this is possible or even if it exist, but I'm very curious to find out. I don't want to give the wrong ideas, and describing what I'm trying to achieve before giving out examples definitely will - so I'll just dive right into it.
As far as I know, codes on websites are only ever executed when those websites are accessed by someone. If no one accesses those website, the codes just sit there. The codes have no reason to run if no one's using them, right?
Now what I'm going to propose may sound ridiculous, but please hear me out. I don't know if there is a way to do this, so I'm just going to ask. Is there a way to run those codes without someone accessing the website itself?
Now I know some of you are like, "Huh? What is he talking about? Why would you even want to run the codes if no one is on the website? That literally makes no sense," so I'm going to try and justify why I want something like that to be possible.
For example, if you want to create a script for automatically logging out an user if they've stayed inactive for a certain amount of time, you would need to check whether they've been active in the last (amount of time to wait before logging them out). You can use AJAX to check if they've been active in the last (amount of time to wait before logging them out). If they navigates, or refreshes the page, then it'll reset the counter, and let you know that they've been active in the last (amount of time to wait before logging them out). However, if they do nothing in (amount of time to wait before logging them out), they will be automatically logged out.
If they closed their browser, or exit the tabs that monitors their progress using AJAX, it will no longer monitor their progress, and thus their counter will not be updated, and thus you will have no idea whether they've been active or not. You can't just log them out if they close a tab or a browser, because what if they have multiple tabs or browsers of your website open? Then you would only want to log them out when they closed all of them.
I have other examples, but this is the gist of it. Is there a way to execute codes on a website without the website being accessed by a user? Thank you.
You are looking for cron jobs. They are basically scheduled jobs that run at set times. A cron job can run all kinds of scripts including PHP scripts.
Whether such a script can easily clear expired sessions, I don't know. It will probably depend on the way you store the sessions.
It may be just as easy to implement it in the website. If you store the last activity timestamp of a user, you can just check on a new request whether that timestamp is too old, and if so, delete the session and redirect to the login page. That way, the user officially remains logged in until their next request.
Optionally you may delete old sessions that are remembered by PHP. See related question: Cleanup PHP session files.
One approach is that you could run your PHP scripts on a timer using CRON jobs.
These jobs typically repeat every x hours, minutes, or days.
I'm not sure about the example you provided, though.

Can Firebase/Parse run code at a certain time every day?

Is it possible on Firebase or Parse to set up something kinda like a cron job?
Is there a way to set up some sort of timed operation that runs over the stored user data?
For example, I'm writing a program that allows people to RSVP for lunch everyday. If you have RSVPed by noon, then you get paired up with somebody else who has also RSVPed. Using JavaScript, the user can submit their RSVP in the browser.
The question is, can Firebase/Parse execute the code to match everyone at 12:00pm every day?
Yes, this can be done with Parse. You'll need to write your matching function as a background job in cloud code, and then you'll need to schedule the task in the dashboard. In terms of the flexibility in scheduling, it's not as flexible as cron but you can definitely run a task at the same time every day, or every x minutes/hours.
Tasks can take 15 mins max to execute before they're killed, so depending on the size of your database or the complexity of your task, you may need to break it up into different tasks or make it resumable.
Just to confirm about Firebase:
As #rickerbh said, it can be done with Parse, but currently there is no way for you to run your code on Firebase's server. There are 2 options for you 2 solve this:
You could use Firebase Queue and run your code in Node.js
You could use a different library such as Microsoft Azure (I still haven't tried this yet, I'm not sure if it provides Job Scheduling for Android)
However, Firebase is working on something called Firebase Trigger, which will solve our problem, however it is still not released with no confirmed release date.

Live countdown clock with django and sql?

If I make a live countdown clock like ebay, how do I do this with django and sql? I'm assuming running a function in django or in sql over and over every second to check the time would be horribly inefficient.
Is this even a plausible strategy?
Or is this the way they do it:
When a page loads, it takes the end datetime from the server and runs a javascript countdown clock against it on the user machine?
If so, how do you do the countdown clock with javascript? And how would I be able to delete/move data once the time limit is over without a user page load? Or is it absolutely necessary for the user to load the page to check the time limit to create an efficient countdown clock?
I don't think this question has anything to do with SQL, really--except that you might retrieve an expiration time from SQL. What you really care about is just how to display the timeout real-time in the browser, right?
Obviously the easiest way is just to send a "seconds remaining" counter to the page, either on the initial load, or as part of an AJAX request, then use Javascript to display the timer, and update it every second with the current value. I would opt for using a "seconds remaining" counter rather than an "end datetime", because you can't trust a browser's clock to be set correctly--but you probably can trust it to count down seconds correctly.
If you don't trust Javascript, or the client's clock, to be accurate, you could periodically re-send the current "seconds remaining" value to the browser via AJAX. I wouldn't do this every second, maybe every 15 or 60 seconds at most.
As for deleting/moving data when the clock expires, you'll need to do all of that in Javascript.
I'm not 100% sure I answered all of your questions, but your questions seem a bit scattered anyway. If you need more clarification on the theory of operation, please ask.
I have also encountered the same problem a while ago.
First of all your problem is not related neither django nor sql. It is a general concept and it is not very easy to implement because of overhead in server.
One solution come into my mind is keeping start time of the process in the database.
When someone request you to see remaingn time, read it from database, subtract the current time and server that time and in your browser initialize your javascript function with that value and countdown like 15 sec. After that do the same operation with AJAX without waiting user's request.
However, there would be other implementations depending your application. If you explain your application in detail there could be other solutions.
For example, if you implement a questionnaire with limited time, then for every answer submit, you should pass the calculated javascript value for that second.

How are timed html forms, like the kind you encounter when doing online tests, properly coded using PHP, MySQL, HTML, CSS and JavaScript?

In other words, what technology would take care of doing the time tracking? Would it be the JavaScript? I don't see being able to keep track of such things with PHP.
Here's what I need to accomplish:
I need to have a long form spanning many web page reloads because it is pretty much an online test where each page load displays a new question. However, the entire form, which constitutes one test has a time limit. When the time expires if the user in question has not completed the test then he/she cannot submit a partially completed test nor attempt to do the entire test all over again within the same day (either calendar date or with 12/24 hours in between.) The user may, however, comeback the next day and attempt to finish the entire test again within the allotted time. I know I have added a lot of details and I did this just to show context, nevertheless, the main difficulty for me would be in how accomplish the time expiry feature. That is, somehow, within a series of pages that make up a form representing an online test I want to track the time starting from the first question (one page load) and upon time expiry for the test to be disabled.
Has anyone ever done this? Would anyone have any tips for me on how to accomplish this?
Any advice I can get would totally be appreciated in advance.
If you do track time on client-side - always validate it on the server-side.
Never trust the client, by itself, to validate the time. As mentioned in the comments, client-side time validation is only good for cosmetic features, never for actual validation.
The easiest way to accomplish this is to add a unique token to the form (which is not spoofable) on first navigation. Cookies, or any other sort of session management technique you get from your framework will suffice.
On form submission you can first validate this on client side and return an error if time has passed, even before actually sending the form. If successful, submit the form, and make sure you validate the token upon processing on the server.
There are two ways you could measure the "time they spent" on the form.
When the first page of the form is severed, in the PHP create a session variable containing the date. When they finish the form, you subtract the current date form the beginning date. This gives you the total time it took from when the form was served and finished. However, this is not 100% accurate as there could downtime for other reasons such as slow internet.
You could have JavaScript record the time on that page (I answered how to do that here: here) Using AJAX, this time could be sent that way or by using GET posts. The time would then be kept by PHP somehow and added up in the end.
Hope this helps! Just ask if you want an example.
In the most general terms, you'll need to set up a session on the server side to track each user and test. When the user begins the test, you stamp a variable (server side) with the test start time. As the user progresses through the test and requests additional pages, check whether the difference between the current time and that variable have exceeded the time allowed for the test. If the test has expired, instead of delivering the next test page, you can close up the test and deliver a "time's up" page to the user.
I don't know what server-side environment you're using, but it almost certainly has some sort of session management framework available. To reliably control the testing environment, you have to manage this from the server side.

Categories