How can set wait time in MySQL - javascript

Currently, I have a problem like this:
I add a new user to a table "users" with status set to "new". Then after 5 - 15 minutes the status is changed to "Em". It's dependent on how large the data is.
I would like to make a wait time in mySQL to get the status "Em".
how can I make a wait condition until it changes status, maybe in 5 minutes it has changed status already. how can I count those waits and get the status in every minute of waiting
You can guild me by Javascript it's okay.
Thank you so much

I am not entirely clear what your request is. But here I can provide you with some insight. If we need to trace the elapsed time since the creation of a new user and calculate how long it still needs for the new user to reach the em status, we can use a view. And if we want MySQL to update the status automatically when the time is right, we can use an event scheduler to check periodically.
-- Here is the view supposing it takes 600 seconds to reach em since creation
drop view if exists testview;
create view testview as select user_id,user_status,
concat(time_to_sec(now()) - time_to_sec(ts),' seconds have passed since adding the user.') as since_creation,
concat(time_to_sec(date_add(ts, interval + 600 second)) - time_to_sec(now()),' seconds more to reach em status.') as wait_time
from users
where user_status='new';
-- Here is the event scheduler which checks every 10 seconds
set global event_scheduler=on ;
delimiter //
drop event if exists periodic_check //
create event periodic_check on schedule every 10 second starts now() do
BEGIN
update users set user_status='em' where user_status='new'
and time_to_sec(date_add(ts, interval + 600 second)) - time_to_sec(now()) <=0;
END//

Related

Real time data streaming should change UI based on last received time

I have real time data coming in, based on which I have to change indicator in UI. Meaning if I don't receive data in the last 30 sec , the indicator should turn red. If data is received before thirty 30 sec, it should be green. Note that data comes into the function one after the other. The indicator should change for each data(curveName) in this case.
I have used $timeout and $interval, but unable to crack the problem. Any help will be appreciated.
You can maybe add in your controller something like:
var timer,
timeLimit = 30000; //30s limit
function onDataReceived(data) {
// cancel previous timer
if(timer) $timeout.cancel(timer);
// assuming data is good set indicator to green
$scope.indicator = "green";
// set 30s timer for indicator to go red
timer = $timeout(function(){
$scope.indicator = "red";
}, timeLimit);
}
Depending on how the data is received and your application structure, you can consider using something like:
$scope.$watch('data', onDataReceived);

Is it a smart idea to use setInterval to update a time frequently?

How much of an impact on the server would there be if I used a setInterval like this to continue changing the time displayed in the browser every 10 seconds for example:
setInterval(function(){
var time = moment($('#bidTime').val());
$('#ago').text(time.fromNow());
$('#ago2').text(time.fromNow());
}, 10000);
On the dashboard of my web app, I have a "Last Updated" column with a displayed time that I want to display "xx seconds ago" etc..
Is it bad to use setInterval in this case? Is there a better way?

User scheduled jobs

I would like to allow my users set a schedule when they would like a particular action to occur. I use a node server on azure. I am currently looking at node-schedule and would be making use of it. What I am contemplating is running a master schedule every hour that checks the database for user specified schedules and this schedule sets a new schedule based on the schedules from users. But I don't know if this is a good practice, plus I'm concerned about the server load.
You can use node's cron for that, and accommodate in different ways.
The pseudocode below gives a general idea.
var CronJob = require('cron').CronJob;
new CronJob('0 0 * * * *', function () { // every hour
// check schedules planned for the future, stored as ISODate
DB.getUserSchedule({jobdate:{$gte:Date.now()},
function(userSchedules) {
userSchedules.forEach(sched) {
// convert the date back to a string parsed by cron
var d=extractDayHourMin(sched)
var jobtime = d[4] +' '+d[3]+' '+d[2]+' '+d[1]+' '+d[0]
// setup a new job
var job=new CronJob(jobtime, function() {
performUserJob()
job.stop(); // fires only once
DB.removeUserSchedule(userSchedule);
})});
see https://github.com/ncb000gt/node-cron
However, this is possibly not the best solution : this does creates as much process as schedule, so yes, it would consume more resources than required. Instead of scheduling the schedulers, depending on the granularity of the possible calendar (hour, 1/2 hour, 1/4h), you could also query the db every hour (or 30 or 15mn) to retrieve every date that met, and trigger the appropriate function.
Search Quartz schedule.
My project using that to set the time to send email.

How to code Websockets/AJAX for frequent database updates? Or is there a better method?

I’m making a html & Javascript game and I’m currently trying to write some code that will show the player’s gold balance on the screen and make it decrement by 1 every time the player clicks on a Javascript object (this object is placed in a div on the html page).
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a <div> but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
I don’t want the figure to decrement below 0. Instead, whenever it reaches 0 I want to initiate a Javascript modal to inform the player that they’ve run out of coins.
~~
Originally I was trying to use websockets to display the player’s balance on screen, but I found it very confusing (I’m a beginner at programming in general), so I’m now trying to load the balance on page load, then post the updated balance amount back to my database using AJAX every 60 seconds, or whenever the user closes the browser window, refreshes the page or navigates away from the page. I don’t know if it’s possible to do all these things, or where to start, maybe this is a really bad way to go about this and maybe it's not scalable (maybe the database wouldn't support constant updates from 1000s of players by using this method)?
I would really appreciate any advice or help anyone could give me on any of this.
Thanks in advance!
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
Here are two divs: you store the total number of coins in one and you click the second one to lose coins
<div id="coins">10</div>
<div onCLick="javascript:loseCoin()">If you click here it will cost you 1 coin</div>
Using a function to decrement the cost.
function loseCoin(){
var coins = getElementByid("coins");
var coins_nr = parseInt(coins.innerHTML,10);
if( coins_nr> 0 ){
coins.innerHTML = coins_nr - 1;
} else {
showModal();
}
}
Where showModal() will be your modal (ask if you don't know how to make it)
As for updating the database every 60 sec, you would need a timer loop such as:
setInterval(function () {
// get number of coins from your div's innerHTML
// then call your ajax controller to update DB
}, 60000);
An example of ajax using javascript:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE ) {
if(xhr.status == 200){
console.log(xhr.responseText);
} else {
console.log('something else other than 200 was returned');
}
}
}
xhr.open("POST", "url_of_your_controller_here", true);
xhr.send("coins="+ coins_nr);
(maybe the database wouldn't support constant updates from 1000s of
players by using this method)?
Any decent server should have no problem handling 1000 requests every 60 sec, but it may depend on how many other requests it has and the complexity of your requests.
If you are just trying to decrement a visible counter in the window on each click, you can do something like this:
HTML:
<div id="coinsRemaining">20</div>
code:
// use whatever click handler is appropriate to your app
document.addEventListener("click", function(e) {
var elem = document.getElementById("coinsRemaining");
// get current display text and convert to number
var cnt = +elem.textContent;
--cnt;
if (cnt >= 0) {
elem.textContent = cnt;
}
if (cnt <= 0) {
alert("There are no more coins");
}
});
Working demo: http://jsfiddle.net/jfriend00/s9jb6uhf/
It seems like you don't need to update the database on every click unless there's some realtime aspect of your coin balance that affects other users. If you're just keeping track of your coin balance for future web page visits, then you could update the database much less often than every click.

Increasing value in database after interval of time

i am working on a codeigniter project in which i am making a counter of every movie that is being clicked. Now i want if the user clicks the movie link the user is directed to the movie page and after 30 seconds the counter will be increased to 1. Currently the counter is increased on every click. Any Help???
Here is my view code
Watch in HD
Here is my controller code
public function watch_movie()
{
//$id = $_REQUEST['id'];
$id = $this->input->get('id');
$this->movie_counter->add_counter($id);
//$data['comment'] = $this->site_upload->fetch_comments($id);
//redirect ('site/play_movie', $result);
$this->load->view('Play_movie', $result);
}
Create a Queue!
Every click you insert into the queue, and another job (cronjob) insert every minute (smallest interval) the data from the queue in the correct table.
counter will be increased even every refresh too in this scenario, whateva you are saying for 30 sec interval ( you can use ajax request with a 30 sec timeout) but this seems like a buggy code what if some one closes it before 30 sec (browser) and you don't get any increment....
if you want to setup unique (views) use browser/ip/time based (for generic setup you can make it advance) and every time you get the request of counter addition check your db if you have same ip/browser and less duration as you say(30 sec or 1 min) then don't add other wise add 1 to script.

Categories