feat: support cron jobs

This commit is contained in:
javayhu 2025-08-10 11:13:21 +08:00
parent 7985769871
commit 346d154604
2 changed files with 22 additions and 4 deletions

View File

@ -0,0 +1,18 @@
import { distributeCreditsToAllUsers } from '@/credits/credits';
import { NextResponse } from 'next/server';
/**
* distribute credits to all users daily
*/
export async function GET() {
console.log('distribute credits start');
const { processedCount, errorCount } = await distributeCreditsToAllUsers();
console.log(
`distribute credits end, processed: ${processedCount}, errors: ${errorCount}`
);
return NextResponse.json({
message: `distribute credits success, processed: ${processedCount}, errors: ${errorCount}`,
processedCount,
errorCount,
});
}

View File

@ -559,7 +559,7 @@ export async function addLifetimeMonthlyCredits(userId: string) {
* This function is designed to be called by a cron job * This function is designed to be called by a cron job
*/ */
export async function distributeCreditsToAllUsers() { export async function distributeCreditsToAllUsers() {
console.log('distributing credits to all users start'); console.log('distribute credits start');
const db = await getDb(); const db = await getDb();
@ -572,7 +572,7 @@ export async function distributeCreditsToAllUsers() {
}) })
.from(user) .from(user)
.where(eq(user.banned, false)); // Only active users .where(eq(user.banned, false)); // Only active users
console.log('distributing credits to all users, users count:', users.length); console.log('distribute credits, users count:', users.length);
let processedCount = 0; let processedCount = 0;
let errorCount = 0; let errorCount = 0;
@ -609,7 +609,7 @@ export async function distributeCreditsToAllUsers() {
processedCount++; processedCount++;
} catch (error) { } catch (error) {
console.error( console.error(
`distributing credits to all users error, user: ${userRecord.userId}, error:`, `distribute credits error, user: ${userRecord.userId}, error:`,
error error
); );
errorCount++; errorCount++;
@ -617,7 +617,7 @@ export async function distributeCreditsToAllUsers() {
} }
console.log( console.log(
`distributing credits to all users end, processed: ${processedCount}, errors: ${errorCount}` `distribute credits end, processed: ${processedCount}, errors: ${errorCount}`
); );
return { processedCount, errorCount }; return { processedCount, errorCount };
} }