Delete Firestore documents older than 2 days using React JS - reactjs

Description: I have created a meeting app using ReactJS. In the database, 1 Document contains the data of a single meeting. I want to delete all documents which has been created 2 days. This process can either run all the time in database, or I would prefer, that the process will run every day at 12:00am, which is at night...
const getlink=()=>{
var currentDate = new Date(new Date().getTime() + 48 * 60 * 60 * 1000);
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
const exp = day + "/" + month + "/" + year
const uid=uuid()
db.collection("rooms").doc(uid).set({
roomId:uid,
expire:exp
})
alert("🚨Your (RoomId) is: \n"+uid+"\n\n⚠️ Your Room will expire on - "+exp)
history.push("/")
}
Above is the code I have used for creating a room and saving to a database...
Note: I am using Functional Components... but not Class Based components.. So please try to provide a Functional based answer
Could anyone please help me figure out how to delete the rooms which has been created before 2 days..

You should query all the documents older than 2 days and then iterate the query results and remove them individually.
I would suggest adding a field in your document that stores the timestamp of the creation of that document so you can then query those documents older than 2 days.
To run this process in a specific time you might try using Cloud Functions, you can use Firebase scheduled function or alternatively you can set up a cron job that executes the program every x minutes.
In this other post there are some answers that might be helpful, please check this answer as an example to do the above.

Related

Cron Script to execute a job every 14 days from a given date in specific time zone

I want to execute a Job in CRON for every 14 days from a specific date and timezone.
As an e.g. from JUNE 24TH every 14 days in CST time zone.
Run job every fortnight
The easy way
The easiest way to do this is simply to create the task to run every 14 days from when you want it to first run like:
CREATE TASK mytask_fortnightly
WAREHOUSE = general
SCHEDULE = '20160 MINUTE'
AS
SELECT 'Hello world'
How it works
As there are 60 minutes in an hour, 24 hours in a day and 14 days in a fortnight, ergo that's 20,160 minutes.
Caveat
The above solution does not run the task every fortnight from a given date/time, but rather every fortnight from when the task is created.
Even though this is the simplest method, it does require you to be nominally present to create the task at the exact desired next scheduled time.
As a workaround however, you can create a one-shot task to do that for you the very first time at the exact correct date/time. This means you don't have to remember to be awake / alert / present to do it manually yourself, and you can clean up the creation task afterwards.
The harder way.
Other solutions will require you to create a task which gets run every Thursday (since 2021-06-24 is/was a Thursday, each subsequent Thursday will either be the off-week, or the fortnight week)
e.g. SCHEDULE = 'USING CRON 0 0 * * THU'
Then you will add specific logic to it to determine which one the correct fortnight is.
Using this method will also incur execution cost for the off-week as well to determine if it's the correct week.
Javascript SP
In javascript you can determine if it's the correct week or not by subtracting the start date from the current date and if it's not a mutiple of 14 days, use this as a conditional to short circuit the SP.
const deltaMs = (new Date) - (new Date('2021-06-24'));
const deltaDays = ~~(deltaMs / 86400000);
const run = deltaDays % 14 === 0;
if (!run) return;
// ... continue to do what you want.
SQL
You can also check if it's a fortnight using the following SQL condition in a WHERE clause, or IFF / CASE functions.
DATEDIFF('day', '2021-06-24', CURRENT_DATE) % 14 = 0

EF Core: Simple query - why so slow?

EF Core version: 3.1.
Here's my method:
public static ILookup<string, int> GetClientCountLookup(DepotContext context, DateRange dateRange)
=> context
.Flows
.Where(e => e.TimeCreated >= dateRange.Start.Date && e.TimeCreated <= dateRange.End.Date)
.GroupBy(e => e.Customer)
.Select(g => new { g.Key, Count = g.Count() })
.ToLookup(k => k.Key, e => e.Count);
All fields used are indexed.
Here's generated query:
SELECT [f].[Customer] AS [Key], COUNT(*) AS [Count]
FROM [Flows] AS [f]
WHERE ([f].[TimeCreated] >= #__dateRange_Start_Date_0) AND ([f].[TimeCreated] <= #__dateRange_End_Date_1)
GROUP BY [f].[Customer]
When that query is executed as SQL, the execution time is 100ms.
When that query is used in code with ToLookup method - execution time is 3200ms.
What's even more weird - the execution time in EF Core seems totally independent from the data sample size (let's say, depending on date range we can count hundreds, or hundreds of thousands records).
WHAT THE HECK IS HAPPENING HERE?
The query I pasted is the real query EF Core sends.
The code fragment I pasted first is executed in 3200ms.
Then I took exact generated SQL and executed in as SQL query in Visual Studio - took 100ms.
It doesn't make any sense to me. I use EF Core for a long time and it seem to perform reasonably.
Most queries (plain, simple, without date ranges) are fast, results are fetched immediately (in less than 200ms).
In my application I built a really HUGE query with like 4 multi-column joins and subqueries... Guess what - it fetches 400 rows in 3200ms. It also fetches 4000 rows in 3200ms. And also when I remove most of the joins, includes, even remove the subquery - 3200ms. Or 4000, depending on my Internet or server momentary state and load.
It's like constant lag and I pinpointed it to the exact first query I pasted.
I know ToLookup method causes to finally fetch all input expression results, but in my case (real world data) - there are exactly 5 rows.
The results looks like this:
|------------|-------|
| Key | Count |
|------------|-------|
| Customer 1 | 500 |
| Customer 2 | 50 |
| Customer 3 | 10 |
| Customer 4 | 5 |
| Customer 5 | 1 |
Fetching 5 rows from database takes 4 seconds?! It's ridiculous. If the whole table was fetched, then rows grouped and counted - that would add up. But the generated query returns literally 5 rows.
What is happening here and what am I missing?
Please, DO NOT ASK ME TO PROVIDE THE FULL CODE. It is confidential, part of a project for my client, I am not allowed to disclose my client's trade secrets. Not here nor in any other question. I know it's hard to understand what happens when you don't have my database and the whole application, but the question here is pure theoretical. Either you know what's going on, or you don't. As simple as that. The question is very hard though.
I can only tell the RDBMS used is MS SQL Express running on Ubuntu server, remotely. The times measured are the times of executing either code tests (NUnit) or queries against the remote DB, all performed on my AMD Ryzen 7 8 core 3.40GHz processor. The server lives on Azure, like 2 core of I5 2.4GHz or something like that.
Here's test:
[Test]
public void Clients() {
var dateRange = new DateRange {
Start = new DateTime(2020, 04, 06),
End = new DateTime(2020, 04, 11)
};
var q1 = DataContext.Flows;
var q2 = DataContext.Flows
.Where(e => e.TimeCreated >= dateRange.Start.Date && e.TimeCreated <= dateRange.End.Date)
.GroupBy(e => e.Customer)
.Select(g => new { g.Key, Count = g.Count() });
var q3 = DataContext.Flows;
var t0 = DateTime.Now;
var x = q1.Any();
var t1 = DateTime.Now - t0;
t0 = DateTime.Now;
var l = q2.ToLookup(g => g.Key, g => g.Count);
var t2 = DateTime.Now - t0;
t0 = DateTime.Now;
var y = q3.Any();
var t3 = DateTime.Now - t0;
TestContext.Out.WriteLine($"t1 = {t1}");
TestContext.Out.WriteLine($"t2 = {t2}");
TestContext.Out.WriteLine($"t3 = {t3}");
}
Here's the test result:
t1 = 00:00:00.6217045 // the time of dummy query
t2 = 00:00:00.1471722 // the time of grouping query
t3 = 00:00:00.0382940 // the time of another dummy query
Yep: 147ms is my grouping that took 3200ms previously.
What happened? A dummy query was executed before.
That explains why the results hardly depended on data sample size!
The huge unexplainable time is INITIALIZATION, not the actual query time. I mean, if not the dummy query before, the whole time would elapse on ToLookup line of code! The line would initialize the DbContext, create connection to database and then perform the actual query and fetch the data.
So as the final answer I can say my test methodology was wrong. I measured the time of the first query to my DbContext. This is wrong, the database should be initialized before the times are measured. I can do it by performing any query before the measured queries.
Well, another question appears - why is THE FIRST query so slow, why is initialization so slow. If my Blazor app would use DbContext as Transient (instantiated each time injected) - would it take so much time each time? I don't think so, because it's how my application worked before major redesign. It didn't have noticeable lags (I would notice 3 seconds lag when changing between pages). But I'm not sure. Now my application uses a scoped DbContext, so it's one for user session. So I won't see the initialization overhead at all, so - the method of measuring time after a dummy query seems to be accurate.

Setting a monthly Budget

So I am building a budgeting app for a Salesforce project and I was wondering if there was a way to automatically set a Budget every month.
I have 3 objects: Budget, Account(Custom for finances), Transaction
I suppose I could write a method that subtracts money from Account and adds it to budget but that still doesn't address the fact that I want it to update every month.
public void setFoodBudget() {
//This.Budget = [SELECT BudgetLimit
//FROM Budget__c
//WHERE BudgetCategory = 'Food'];
FoodBudget = 600;
}
If I were to do it manually every month then I could use the query I commented out
I advise you to see schedule batch
https://developer.salesforce.com/forums/?id=9062I000000IEIhQAO

how to get date and compare it while indexing

I want to make a bust for latest data while indexing my content. For example
Content from now to 6 months past should have boost = 10
and Content from 6 month past to 12 month past should have boost = 5
Older content should have boost = 0
my date is saved as timestamp so the only problem is to get current date while indexing
I can get date of content from row that is a param in my function but I don't know how to get current date and compare it. should it be something like this ?
and one more question
is there some way to check the boost ? I mean can i monitor what is boosted how ? Cause using result list with couple thousands articles is hard to mesure
// EDIT ANSWER
GOT IT
The script should look like this (this is for one 1 year past and older
<script>
<![CDATA[
function s1(row) {
var curTime = parseInt(new Date().getTime()/1000);
var itemDate = row.get('publication_date');
if(itemDate >= (curTime - 31104000)) {
row.put('$docBoost', 40);
} else {
row.put('$docBoost', 20);
}
return row;
}
]]>
</script>
I would recommend using query/search time boosting instead for your use case. The main advantage is that you don't need to reindex your documents periodically to adjust boosts. See Date Boosting and "How can I boost the score of newer documents" wiki tips

How to query google app engine blobstore by creation date and order the results

I need to retrieve the latest set of files from GAE blobstore. Currently my code says
nDays = 10 #this is set at run time
gqlQuery = blobstore.BlobInfo.gql("WHERE filename = :1 ORDER BY creation DESC",<filename>)
cursor = gqlQuery.fetch(nDays)
when I iterate and print out the data by calling cursor[i].creation, it doesn't give me the last nDays starting from today. For example, today is August 20. I expect it to give me data from Aug 11 - Aug 20 (I have a file for each day). Instead it gives me data from Aug 13 back a few days.
If i remove the ORDER BY in the gqlquery, it correctly returns all the results (not sorted).
If I make the gqlQuery iterable so that I say something like
for filename in gqlQuery:
print filename.creation
it only prints from August 13 back to a few days (about 8 days). I know for a fact there is data up till today. From GAE, I can view the data. Also, the creation date is stamped automatically by Google when the file is uploaded to blobstore.
Anyone know what I'm missing?
I may also miss something, but what's the purpose of "filename = :1" in you query?
This ran correctly against my blobstore:
gqlQuery = blobstore.BlobInfo.gql("ORDER BY creation DESC")
blobs = gqlQuery.fetch(5)
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write("Lasts blobs<br>")
for blob in blobs:
self.response.out.write(blob.filename + "<br>")
Florent

Resources